简体   繁体   中英

How to select descendant nodes of XML in c#?

Here is my XML Variable called test having following 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>

I'm creating result XML variable using following c# code,

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

Above code is throwing null exception.

I need the following output 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>

Any Help appreciated! :)

You can try this way :

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>

To get all nodes use XPath expression /Names/Name. The first slash means that the node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the nodes.

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM