Search code examples
c#xmlxelement

Convert XmlElement to XElement with Elements("ElementName") Returns No Results


I'm using the following code to convert a XmlElement to XElement

public staic XElement ToXElement(this XmlNode node) {
    XElement element = null;
    if (null != node) {
        element = XElement.Parse(node.OuterXml);
    }
    return element;
}

However when I call Elements() or Elements("ElementName") I get no results.
I do however get results from calling Nodes().

Why don't the elements come up from calling Elements and what's the difference between the two methods?

Here is a snippit of the xml I'm parsing.

<Feature xmlns="http://schemas.microsoft.com/sharepoint/">
    <ElementManifests>
        <ElementFile Location="Path/file.xml"/>
    </ElementManifests>
</Feature>

Solution

  • You are probably not using the namespace correctly. Both of these methods work correctly for me:

    XElement root = XElement.Load("test.xml"); //or result of ToXElement
    foreach(var item in root.Elements())
    {
        Console.WriteLine(item.Name);
    }
    
    XNamespace ns = "http://schemas.microsoft.com/sharepoint/";
    var manifestsNode = root.Element(ns + "ElementManifests");
    

    Given that you don't know the difference between the Elements() (get all direct children) and Element() (get one specific direct child element) you should start with a Linq to Xml tutorial.