在 XML 文档中选择节点时返回 Null [英] Null returned when selecting a node in XML document
问题描述
XML 新手.我有一个 3rd 方网络服务,它提供一个 XML 文档,我必须更新元素值并传回.核心问题是在下面的代码中调用 node.RemoveAll() 方法时出现 NullReferenceException 错误.我正在调用 RemoveAll() 方法,因为每个元素在提供给我时都具有 xsi:nil 属性,如果我在更新元素值之前不删除它,则 Web 服务不会验证 XML.
New to XML. I have a 3rd party webservice that supplies an XML document that I have to update the element values and pass back. The core issue issue is I get an NullReferenceException error when calling the node.RemoveAll() method in the code below. I'm calling the RemoveAll() method because each element has the xsi:nil attribute when it is supplied to me, and if I don't remove it before updating the element value, the XML won't validate by the webservice.
第三方webservice提供的XML文档如下:
The XML document supplied by the 3rd party webservice is as follows:
<?xml version="1.0" encoding="utf-16"?>
<TaskData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.sample.com/application/1/520800B">
<Global>
<RequestInfo xmlns="http://schema.sample.com/application/1/Types">
<Requestor xsi:nil="true" />
<Date_init xsi:nil="true" />
<Shipto xsi:nil="true" />
<Customer xsi:nil="true" />
<Contact xsi:nil="true" />
<Requestor_Email xsi:nil="true" />
</RequestInfo>
</Global>
</TaskData>
我见过的其他解决方案使用了 XmlNamespaceManager,但我一直无法使其工作.此 xml 文档具有为 TaskData 元素指定的命名空间,以及为 RequestInfo 元素指定的不同命名空间.我尝试为每个命名空间指定 XmlNamespaceManager 变量,但得到了相同的结果......在中断模式下将鼠标悬停在 nsmgr 变量上显示无法评估子级"并且 DefaultNamespace 属性是一个空字符串.
Other solutions I've seen have used the XmlNamespaceManager, but I haven't been able to make it work. This xml document has a namespace specified for the TaskData element, and a different namespace for the RequestInfo element. I tried specifying the XmlNamespaceManager variable for each namespace, but got the same results....hovering over the nsmgr variable while in break mode reveals that the "children could not be evaluated" and that the DefaultNamespace property is an empty string.
Public Sub testxml()
Dim doc As New XmlDocument
doc.Load("c:\temp\sample.xml")
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("s", "http://schema.sample.com/application/1/520800B")
Dim node As XmlNode = doc.SelectSingleNode("s:Requestor", nsmgr)
node.RemoveAll()
node.InnerText = "Your Name Goes Here"
doc.Save("c:\temp\sample.xml")
End Sub
推荐答案
问题在于这个声明:
doc.SelectSingleNode("s:Requestor", nsmgr)
你需要做的是
doc.SelectSingleNode("//s:Requestor",nsmgr)
"s:Requestor" 表示给我当前节点名称 s:Requestor 下的节点
"s:Requestor" means give me the node underneath the current node name s:Requestor
"//s:Requestor" 表示给我名为 s:Requestor 的文档中的所有节点
"//s:Requestor" means give me all nodes in the document named s:Requestor
如果你想忽略命名空间,你可以这样做
if you want to ignore the namespace you could do
doc.SelectSingleNode("//*[local-name()='Requestor']")
这篇关于在 XML 文档中选择节点时返回 Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!