Working around XML namespaces
Oct 7
2011
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 => !x.IsNamespaceDeclaration)
.Select(x => 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.
No new comments are allowed on this post.
Comments
Vamsi
Thanks a lot for saving me time. This helped me to overcome namespaces. Thx again!!