Search code examples
c#xmllinqxelement

XElement - reading the nodes C#


I have an XML like below:

<?xml version="1.0"?>
<productfeed>
    <product>
        <name>x</name>
        <etc>z</etc>
    </product>
    <product>
        <name>x</name>
        <etc>z</etc>
    </product>
</productfeed>

I tried today LINQ and XElement to retrieve the data from the XML. I manage to load the file, however I cannot access productfeed node (it returns null). Interestingly I can iterate through product nodes straight from the root, while I read that one should not skip like that. Do I interpret something wrongly, perhaps productfeed node is already in the root, but then how would I get its pure contents?

XElement root = XElement.Load("...path..."); // works
XElement productFeed = root.Element("productfeed"); // returns null
IEnumerable<XElement> products = root.Elements("product"); // works

Solution

  • Formally you should load this into an XDocument. That would have had a <productfeed> element as a Root property.

    XElement lets you skip this step, it can act as Document and root at the same time. The fix is very simple:

    XElement productFeed = root; //.Element("productfeed"); 
    

    XElement and XDocument do Parse the same content but XDocument has a (more complete) document wrapper, you will need that when dealing with the <? > Processing Instructions etc.