roger.james
roger.james

Reputation: 1498

Getting an XML element

In the following program, helloElem is not null, as expected.

string xml = @"<root>
<hello></hello>
</root>";

XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Root.Element("hello"); //not null

If give the XML a namespace:

string xml = @"<root xmlns=""namespace"">
<hello></hello>
</root>";

XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Root.Element("hello"); //null

why does helloElem become null? How do I get the hello element in this case?

Upvotes: 1

Views: 122

Answers (4)

Cylian
Cylian

Reputation: 11181

Surely you can get rid of namespaces, see below:

string xml = @"<root>
                   <hello></hello>
               </root>";

 XDocument xmlDoc = XDocument.Parse(xml);
 var helloElem = xmlDoc.Descendants().Where(c => c.Name.LocalName.ToString() == "hello");

Above code could handle nodes with or without namespaces. See Descendants() for more information. Hope this helps.

Upvotes: 3

Dustin Kingen
Dustin Kingen

Reputation: 21275

Here is a default namespace XPath.

private static XElement XPathSelectElementDefaultNamespace(XDocument document,
                                                           string element)
{
    XElement result;
    string xpath;

    var ns = document.Root.GetDefaultNamespace().ToString();

    if(string.IsNullOrWhiteSpace(ns))
    {
        xpath = string.Format("//{0}", element);
        result = document.XPathSelectElement(xpath);
    }
    else
    {
        var nsManager = new XmlNamespaceManager(new NameTable());
        nsManager.AddNamespace(ns, ns);

        xpath = string.Format("//{0}:{1}", ns, element);
        result = document.XPathSelectElement(xpath, nsManager);
    }

    return result;
}

Usage:

string xml1 = @"<root>
<hello></hello>
</root>";

string xml2 = @"<root xmlns=""namespace"">
<hello></hello>
</root>";

var d = XDocument.Parse(xml1);
Console.WriteLine(XPathSelectElementDefaultNamespace(d, "hello"));
// Prints: <hello></hello>

d = XDocument.Parse(xml2);
Console.WriteLine(XPathSelectElementDefaultNamespace(d, "hello"));
// Prints: <hello xmlns="namespace"></hello>

Upvotes: 1

Damith
Damith

Reputation: 63105

do as below

XDocument xmlDoc = XDocument.Parse(xml);
XNamespace  ns = xmlDoc.Root.GetDefaultNamespace();
var helloElem = xmlDoc.Root.Element(ns+ "hello"); 

Upvotes: 2

Bala R
Bala R

Reputation: 109037

Try

 XNamespace ns = "namespace";
 var helloElem = xmlDoc.Root.Element(ns + "hello"); 

Upvotes: 2

Related Questions