Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing of XML string (with namespace) using LINQ

My Input

<A xmlns="http://abc.com"> 
    <B>"b"</B>
    <C>"c"</C>
    </A>

My Code

XNamespace ns = XNamespace.Get("http://abc.com");

var query= from node in doc.Descendants(ns+ "A") 
           select new
            (
                        B = (string)node.Element(ns+"B"),
                            C = (string)node.Element(ns+ "C")
             );

My Question

Do I have to add ns every time I am doing node.Element()? or is there any other way?

like image 820
Eternal Noob Avatar asked Oct 05 '12 21:10

Eternal Noob


People also ask

Does Linq work with XML?

The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes.


1 Answers

Do I have to add ns every time I am doing node.Element()?

Yes, basically. You're looking for (say) an element with a local name of B and a namespace URI of "http://abc.com".

You could write your own extension method which matched any element with the right local name, but I'd advise against it. It would be something like:

public IEnumerable<XElement> ElementsWithLocalName(this XContainer container,
    string localName)
{
    return container.Elements().Where(x => x.Name.LocalName == localName);
}

public IEnumerable<XElement> ElementsWithLocalName<T>(
    this IEnumerable<T> source,
    string localName) where T : XContainer
{
    return source.Elements().Where(x => x.Name.LocalName == localName);
}

This would make your code less reliable though - do you really want to match just any old name with the right local name?

like image 82
Jon Skeet Avatar answered Sep 18 '22 23:09

Jon Skeet