Parsing an XML string (with namespace) using LINQ
My entry
<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 need to add ns every time I do node.Element() ? or is there any other way?
+6
1 answer
Do I need to add ns every time I do node.Element ()?
Yes, in principle. You are looking for (say) an element with the local name B and namespace URI "http://abc.com".
You can write your own extension method that matches any element with the correct local name, but I would recommend it. It will 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 will make your code less reliable, though ... do you really want to combine any old name with the correct local name?
+8