Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to XML - accessing descendants with a prefix

Tags:

c#

xml

linq

I have a sample xml file like this

<vs:BioData>
<vs:Name>Name</vs:Name>
<vs:Address>address</vs:Address>
<vs:Zip>Zip</vs:zip>
</vs:BioData>

All the nodes have a prefix value as vs and can anyone tell me how would I go about parsing this file to read Name and Address Information? I am very new to LINQ. Any help on this would be greatly appreciated.

Thanks!

like image 661
Venki Avatar asked Mar 31 '11 14:03

Venki


2 Answers

You need to know what the namespace is. That will have been declared earlier, with something like:

xmlns:vs="http://some_url_here"

You can query using XNamespace:

XNamespace vs = "http://some_url_here";
var names = doc.Descendants(vs + "Name")
               .Select(x => (string) x)
               .ToList();

The + here is actually converting an XNamespace and a string to an XName.

like image 130
Jon Skeet Avatar answered Oct 08 '22 02:10

Jon Skeet


The prefix "vs" should be mapped to a namespace in the header of the XML document, eg:

<FooDocument xmlns:vs="http://schemas.example.com/vs">

Then you can select those elements with LINQ by using an XNamespace, like this:

XNamespace vs = "http://schemas.example.com/vs";

var names = myXDoc.Root.Descendants(vs + "Name");

The XNamespace and XName types all support implicit conversion from strings.

like image 38
Chris Wenham Avatar answered Oct 08 '22 02:10

Chris Wenham