6

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?

Eternal Noob
  • 2,717
  • 5
  • 27
  • 41
  • 1
    There's a related question here, too: http://stackoverflow.com/questions/2610947/search-xdocument-with-linq-with-out-knowing-the-namespace – dash Oct 05 '12 at 21:37
  • I believe `XPath` could offer an alternative, but it's more complicated than what you're doing here. – neontapir Oct 05 '12 at 21:57

1 Answers1

8

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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • No I do not _really_ want to do that, but I thought doc.Descendants(ns+ "A") makes sense, but for children nodes isn't that redundant information? Doesn't it imply that any node under A would have same namespace URI as A's namespace URI? – Eternal Noob Oct 05 '12 at 22:43