如何在使用 c# 定义键值对时将包装器添加到当前 xml

本文关键字:添加 包装 xml 键值对 定义 | 更新日期: 2023-09-27 18:31:40

我需要为我当前的 xml 提供包装器,我从中获取 keyvalye 对值。这是我当前的代码:

string SID_Environment = "SID_" + EnvironmentID.ToString();
XDocument XDoc = XDocument.Load(FilePath_EXPRESS_API_SearchCriteria);
var Dict_SearchIDs = XDoc.Elements().ToDictionary(a => (string)a.Attribute("Name"), a => (string)a.Attribute("Value"));
string Search_ID = Dict_SearchIDs.Where(IDAttribute => IDAttribute.Key == SID_Environment).Select(IDAttribute => IDAttribute.Value).FirstOrDefault();
Console.WriteLine(Search_ID);

这是我的示例 xml,如下所示:

<APIParameters>
     <Parameter Name="SID_STAGE" Value="101198" Required="true"/>
     <Parameter Name="SID_QE" Value="95732" Required="true"/>
 </APIParameters>

请注意,此代码在示例 xml 中工作正常,但在使用一些包装器修改我的 xml 后,我遇到了这个问题。我需要为我的 xml 提供一些包装器来修改我的示例 xml,如下所示:

<DrWatson>
  <Sets>
    <Set>
      <APIParameters>
        <Parameter Name="SID_STAGE" Value="101198" Required="true"/>
        <Parameter Name="SID_QE" Value="95732" Required="true"/>
      </APIParameters>
    </Set>
  </Sets>
</DrWatson>

但是当我这样做并运行我的代码时,它会给我一个错误。请指教。

如何在使用 c# 定义键值对时将包装器添加到当前 xml

XDoc.Elements() 只返回直接的子元素,请改用后代。

var parameterElements = xDoc.Descendants("Parameter");
parameterElements.ToDictionary(a => (string)a.Attribute("Name"), 
                               a => (string)a.Attribute("Value"));

你需要这样的东西:

var apiParams = doc.Descendants("APIParameters");

然后,您可以修改代码:

var Dict_SearchIDs = apiParams.Elements().ToDictionary(a => (string)a.Attribute("Name"), a => (string)a.Attribute("Value"));