Ve said:
But how can I check if the xml is containing a default namespace ?
How to delete default namespace from XmlDocument?
How to get name of the default namespace ?
Generally for your DOM and XPath processing it should not matter whether
a default namespace (e.g. xmlns="
http://example.com/ns1") or a normal
namespace declaration (e.g. xmlns
f="
http://example.com/ns1") is
applied, you simply want to know whether an element or attribute node is
in a certain namespace or not. For that in the DOM model you can check
the NamespaceURI property of an element or attribute node
<URL:
http://msdn2.microsoft.com/en-us/library/system.xml.xmlnode.namespaceuri.aspx>.
The DOM implementation in the .NET framework also exposes two methods
GetNamespaceOfPrefix
<URL:
http://msdn2.microsoft.com/en-us/library/system.xml.xmlnode.getnamespaceofprefix.aspx>
and GetPrefixOfNamespace
<URL:
http://msdn2.microsoft.com/en-us/library/system.xml.xmlnode.getprefixofnamespace.aspx>
that help dealing with namespaces.
So to get the name (URI) of the default namespace defined on the root
element you can do
doc.DocumentElement.GetNamespaceOfPrefix("")
and you can check the result against the empty string to find out
whether a default namespace declaration exists.
doc.LoadXml(
"<root xmlns=\"
http://example.com/ns1\"><foo>bar</foo></root>");
Console.WriteLine("GetNamespaceOfPrefix(\"\"): \"{0}\".",
doc.DocumentElement.GetNamespaceOfPrefix(""));
// GetNamespaceOfPrefix(""): "
http://example.com/ns1".
doc.LoadXml("<root><foo>bar</foo></root>");
Console.WriteLine("GetNamespaceOfPrefix(\"\"): \"{0}\".",
doc.DocumentElement.GetNamespaceOfPrefix(""));
// GetNamespaceOfPrefix(""): "".
As for removing a namespace, that is technically not possible, at least
not in the way that you can change the namespace a node is in, the
NamespaceURI property of a node is readonly. So you need to create new
nodes in no namespace. An XSLT stylesheet is good at implementing such
transformations:
<xsl:stylesheet
xmlns:xsl="
http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@* | node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@* | comment() | processing-instruction() |
text()">
<xsl:copy/>
</xsl:template>
</xsl:stylesheet>
This stylesheet strips any namespace from element nodes in the input XML
document. XSLT transformations can be applied using
System.Xml.Xsl.XslCompiledTransform.