简体   繁体   中英

Unable to fetch xml node using XDocument.Element

Here is a sample XML wherein I want to fetch xml node.

XDocument doc = XDocument.Load("PurchaseOrder.xml");

<Rootelement>
    <element1 />
    <element2 />
    <element2 />
    <element3 />
</Rootelement>

I want to find out element2 from the xml

Here is my code snippet.

var xElement = XDoc.Element("Rootelement").Element("element2");

but I shows null. I do not have any namespace in xml and I can't include one.

Please help.

 XmlDocument xml = new XmlDocument();
    xml.LoadXml(myXmlString);

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

This code will return all the values of the tag <firstName> and <LastName> . If you only want one value then you can remove the foreach loop and you are good to go.

Here is the xml code

<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

Try like this;

var xElement = doc.Root.Element("element2");

If you want to find elements anywhere in the document Use;

doc.Descendants("element2")

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