Daniel Little Daniel Little - 1 year ago 141
C# Question

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

I'm using the following code to convert a


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

However when I call
I get no results.

I do however get results from calling

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/">
<ElementFile Location="Path/file.xml"/>

Answer Source

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())

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download