Working around XML namespaces

You are looking at revision 2 of this page, which may be out of date. View the latest version.  

Every time I go to work with XML that contains namespaces I get frustrated at having to do what seems like extra work. I have never had to deal with XML naming conflicts so namspaces just seem like a waste of time.

For example let's say we are dealing Linq to XML and have a XDocument

var xDocument = XDocument.Parse(
@"<root>
    <f:table xmlns:f=""http://www.w3schools.com/furniture"">
        <f:name>African Coffee Table</f:name>
        <f:width>80</f:width>
        <f:length>120</f:length>
    </f:table>
  </root>");

Now to get the table element I need to qualify the namespace

var qualifiedName = XName.Get("table", "http://www.w3schools.com/furniture");
var tables = xDocument.Descendants(qualifiedName);

But why do I need the namespace? There is only one "table" type in the XML. I want to be able to write this.

var tables = xDocument.Descendants("table");

So I wrote this little helper class.

public static class XmlExtensions
{
    public static void StripNamespace(this XDocument document)
    {
        if (document.Root == null)
        {
            return;
        }
        foreach (var element in document.Root.DescendantsAndSelf())
        {
            element.Name = element.Name.LocalName;
            element.ReplaceAttributes(GetAttributes(element));
        }
    }

    static IEnumerable GetAttributes(XElement xElement)
    {
        return xElement.Attributes()
            .Where(x =&gt; !x.IsNamespaceDeclaration)
            .Select(x =&gt; new XAttribute(x.Name.LocalName, x.Value));
    }
}

Now I can write this

var xDocument = XDocument.Parse(
@"<root>
    <f:table xmlns:f=""http://www.w3schools.com/furniture"">
        <f:name>African Coffee Table</f:name>
        <f:width>80</f:width>
        <f:length>120</f:length>
    </f:table>
  </root>");

xDocument.StripNamespace();
var tables = xDocument.Descendants("table");

I just wish the .net XML APIs came with a "I don't care about namespaces" option.

Posted by: Simon Cropp
Last revised: 21 May, 2013 11:26 AM History
You are looking at revision 2 of this page, which may be out of date. View the latest version.

Comments

No comments yet. Be the first!

No new comments are allowed on this post.