Working with XDocument and Namespaces
I really like working with the new LINQ support for XML files. However, every time I work with a document that has namespaces, I stumble. For some reason, I just can’t remember all the details required to be able to use XPath expressions when you have namespaces defined in an XML file. A blog post, therefore, seems like a good idea.
Default Namespace
A common case is where an XML file has a default namespace defined at the very top. For example,
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<RootNamespace>Test</RootNamespace>
<AssemblyName>Test</AssemblyName>
<OutputType>Library</OutputType>
</PropertyGroup>
...
return doc.Root.XPathSelectElement("PropertyGroup/RootNamespace").Value
XmlNamespaceManager namespaces = new XmlNamespaceManager(new NameTable());
XNamespace ns = _doc.Root.GetDefaultNamespace();
namespaces.AddNamespace("ns", ns.NamespaceName);
return doc.Root.XPathSelectElement("ns:PropertyGroup/ns:RootNamespace", namespaces).Value;
6 Comments:
Thank you! That helped solve my dilemma. I couldn't figure out the correct syntax originally to query the XElement that had a namespace - your solution worked.
Excellent. If the parent node has a namespace then that applies to all the child elements under that element even if it is not explicitely specified. That is why we need to prefix it with the namespace.
Thanks ... It worked exactly the way i wanted.
fantastic
Thanks, this helped me.
Thanks lot, this helped me.
Post a Comment
<< Home