开发者

Why the need for XmlNamespaceManager when parsing XML

So when I was getting a null value using selectSingleNode, I found that I needed to declare a namespace because I was using the xmlns attribute. My question is why I need to use a prefix when parsing the xml, if I don't use the prefix in the xml file itself?

The reason I have the xmlns attribute, is because the receiving end of my xml output requires it. I would rather read it in from the base xml than have it开发者_JS百科 hardcoded in the program.

This is the code that works

xmlns = New XmlNamespaceManager(xmlTemplate.NameTable)
xmlns.AddNamespace("dc", ns)

I tried doing this - doesn't work

xmlns = New XmlNamespaceManager(xmlTemplate.NameTable)
xmlns.AddNamespace(String.Empty, ns)

In short, is there any way to get rid of the "dc" prefix?


This is just one of those "that's the way they built it" kind of things. According to MSDN (XPath Queries with Namespaced Mapped Prefixes):

The XmlNamespaceManager allows adding default namespaces by using an empty string as the prefix. However, XPath treats the empty prefix as the null namespace. In other words, only prefixes mapped to namespaces can be used in XPath queries. If you want to use the default namespace from an XML document in the XPath expression, then you need to define a prefix for it.

And also from MSDN (XmlNamespaceManager.AddNamespace):

If the XmlNamespaceManager will be used for resolving namespaces in an XML Path Language (XPath) expression, a prefix must be specified. If an XPath expression does not include a prefix, it is assumed that the namespace Uniform Resource Identifier (URI) is the empty namespace

EDIT

And I'm assuming your code is something like:

Dim S = "<xml xmlns=""http://www.exmaple.com/""><node/></xml>"

Dim X As New Xml.XmlDocument()

X.LoadXml(S)
Dim NS As New Xml.XmlNamespaceManager(X.NameTable)
NS.AddNamespace("dc", "http://www.exmaple.com/")

''//Will not work
Dim N1 = X.SelectSingleNode("//xml/node", NS)
If N1 Is Nothing Then
    Trace.WriteLine("Node not found")
Else
    Trace.WriteLine("Node found")
End If

''//Works
Dim N2 = X.SelectSingleNode("//dc:xml/dc:node", NS)
If N2 Is Nothing Then
    Trace.WriteLine("Node not found")
Else
    Trace.WriteLine("Node found")
End If


You should be able to get the namespace from the incoming XML instead of having to hardcode it by doing:

NS.AddNamespace("dc",X.DocumentElement.Attributes("xmlns").InnerText)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜