11

I'm new to working with XML, and I've encountered a weird problem while trying to get a specific tag from a spring.net configuration file. After trying to narrow down the problem with a test xml file, I found out that applying the following code:

List<XElement> nodes = xmlFile.Descendants("B").ToList();

provides a non-empty list with the following file:

<?xml version="1.0" encoding="utf-8" ?>
<A fakeAttribute="aaa">
  <B id="DbProvider"/>
</A>

but provides an empty string with the following file:

<?xml version="1.0" encoding="utf-8" ?>
<A xmlns="aaa">
  <B id="DbProvider"/>
</A>

The only difference between the files being the attribute.

I can't imagine an explanation for this. Thanks for your help.

3 Answers 3

10

You need to search for tags in that namespace:

XNamespace ns = "aaa";

xmlFile.Descendants(ns + "B").ToList()
3
  • Thanks! That did the trick - but also opened the way to another problem. I can obtain descendants named "B", for example, but cannot obtain descendants named "db:provider" (not by using "db" nor "db:provider"), which is sadly exactly what I need to do.
    – Tomata
    Commented Oct 16, 2011 at 17:07
  • db is listed as a different namespace. My bad.
    – Tomata
    Commented Oct 16, 2011 at 17:12
  • 4
    @Tomata If you want to ignore namespaces you can write something like: var lst = doc.Descendants().Where(p => p.Name.LocalName == "B").ToList();
    – xanatos
    Commented Oct 16, 2011 at 17:41
10

Just for completeness sake:

var lst = doc.Descendants("{aaa}B").ToList();

(what the other told is correct, but I wanted to give another option :-) )

For ultra completeness-sake, if you want to search ignoring the namespace:

var lst = doc.Descendants().Where(p => p.Name.LocalName == "B").ToList();
7

You should specify the namespace when querying for the elements.

You can use the GetDefaultNamespace method to avoid hard-coding it. It's also useful if you don't know what it is ahead of time.

Example:

var ns = xmlFile.GetDefaultNamespace();
var nodes = xmlFile.Descendants(ns + "B").ToList();
1
  • 1
    In one case, .GetDefaultNamespace didn't work because the XML schema author wasn't using xmlns but rather xmlns:foo. You can use: var ns = xDoc.Root.GetNamespaceOfPrefix("foo");
    – Stonetip
    Commented Aug 27, 2012 at 22:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.