XML 新手。我有一个第 3 方 Web 服务,它提供一个 XML 文档,我必须更新元素值并传回。核心问题是在下面的代码中调用 node.RemoveAll() 方法时出现 NullReferenceException 错误。我正在调用 RemoveAll() 方法,因为每个元素在提供给我时都具有 xsi:nil 属性,如果我在更新元素值之前不删除它,则 Web 服务不会验证 XML。
第 3 方 Web 服务提供的 XML 文档如下:
<?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 属性是一个空字符串。
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