Reputation: 1498
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
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
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
Reputation: 63105
do as below
XDocument xmlDoc = XDocument.Parse(xml);
XNamespace ns = xmlDoc.Root.GetDefaultNamespace();
var helloElem = xmlDoc.Root.Element(ns+ "hello");
Upvotes: 2
Reputation: 109037
Try
XNamespace ns = "namespace";
var helloElem = xmlDoc.Root.Element(ns + "hello");
Upvotes: 2