如何在 c# 中选择 XML 的后代节点



这是我的XML变量,名为test具有以下XML,

<A>
      <X>
        <B  id="ABC">
          <C name="A" />
          <C name="B" />
          <C name="C" />
          <C name="G" />
        </B>
        <B id="ZYZ">
          <C name="A" />
          <C name="B" />
          <C name="C" />
          <C name="D" />
        </B>
      <X>
</A>

我使用以下 c# 代码创建result XML 变量,

var result = new XElement(
                    "Result",
                    new[]
                        {                          
                            new XElement("First",test.Descendants("X"))
                        }
                        );

上面的代码抛出空异常。

我需要以下输出 XML,

<Result>
  <B  id="ABC">
              <C name="A" />
              <C name="B" />
              <C name="C" />
              <C name="G" />
            </B>
  <B id="ZYZ">
              <C name="A" />
              <C name="B" />
              <C name="C" />
              <C name="D" />
  </B>
</Result>

任何帮助感谢! :)

你可以试试这种方式:

var xml = @"<A>
      <X>
        <B  id=""ABC"">
          <C name=""A"" />
          <C name=""B"" />
          <C name=""C"" />
          <C name=""G"" />
        </B>
        <B id=""ZYZ"">
          <C name=""A"" />
          <C name=""B"" />
          <C name=""C"" />
          <C name=""D"" />
        </B>
      </X>
</A>";
var doc = XDocument.Parse(xml);
var newDoc = new XElement("Result", doc.Root.Element("X").Elements());
//this will print the same output as you expect (the 2nd XML in question)
Console.WriteLine(newDoc.ToString());
<Names>
<Name>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
</Name>
<Name>
    <FirstName>James</FirstName>
    <LastName>White</LastName>
</Name>

要获取所有节点,请使用 XPath 表达式/Names/Name。第一个斜杠表示节点必须是根节点。SelectNodes方法返回集合XmlNodeList,它将包含节点。

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
 string firstName = xn["FirstName"].InnerText;
 string lastName = xn["LastName"].InnerText;
 Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
var result = new XElement("Result", test.Descendants("B"));

最新更新