Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use Descendants() or Elements() with xmlns

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.

like image 914
Tomata Avatar asked Oct 16 '11 16:10

Tomata


1 Answers

You need to search for tags in that namespace:

XNamespace ns = "aaa";

xmlFile.Descendants(ns + "B").ToList()
like image 156
SLaks Avatar answered Oct 20 '22 00:10

SLaks