I have a simple XML,
<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><H></H></S>
I want to find all "H" nodes.
XElement x = XElement.Parse("<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><H></H></S>");
IEnumerable<XElement> h = x.Descendants("H");
if (h != null)
{
}
But this code doesn't work. When I remove the namespace from S tag, the code works correctly.
Your element has a namespace because xmlns
effectively sets the default namespace for that element and its descendants. Try this instead:
XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
IEnumerable<XElement> h = x.Descendants(ns + "H");
Note that Descendants
will never return null, so the condition at the end of your code is pointless.
If you want to find all H
elements regardless of namespace, you could use:
var h = x.Descendants().Where(e => e.Name.LocalName == "H");
Just wanted to add to Jon's answer that you can get the namespace like this:
XNamespace ns = x.Name.Namespace
Then just use it like he proposed:
IEnumerable<XElement> h = x.Descendants(ns + "H");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With