我创建了一个 xml-fil 并遇到了问题。我已尽可能简化了代码以显示错误。我的项目中引用了 Microsoft XML 6.0。当我运行这段代码时
Sub simpleTest()
Dim xDoc As New DOMDocument60
Dim n0 As IXMLDOMNode
Dim n1 As IXMLDOMElement
Dim n2 As IXMLDOMElement
Dim blValiderad As Boolean
Const file = "c:\temp\abc.xml"
xDoc.async = False
xDoc.validateOnParse = False
xDoc.resolveExternals = False
xDoc.preserveWhiteSpace = True
Set n0 = xDoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
xDoc.appendChild n0
Set n1 = xDoc.createElement("Document")
n1.setAttribute "xmlns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
n1.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"
Set n2 = xDoc.createElement("CstmrCdtTrfInitn")
n2.Text = "hello"
n1.appendChild n2 'CstmrCdtTrfInitn
xDoc.appendChild n1 'Document
xDoc.Save file
End Sub
它生成这个 xml 表达式
<?xml version="1.0"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrCdtTrfInitn xmlns="">
hello
</CstmrCdtTrfInitn>
</Document>
验证时会产生此错误:
1072897501; Validate failed because the document does not contain exactly one root node.
问题似乎出在 CstmrCdtTrfInitn 的空属性 xmlns="" 上。当我从文件中删除它时,没有验证错误。为什么会这样?为什么它是由我的代码生成的?
最佳答案
据我了解, CreateElement("some_text")
是 createNode(Type:=NODE_ELEMENT, Name:="some_text", NamespaceURI:="")
.
由于 NamespaceURI 与父元素不匹配,因此会创建该属性。
相反,使用createNode
并指定命名空间:
Dim xDoc As New DOMDocument60
Dim n0 As IXMLDOMNode
Dim n1 As IXMLDOMElement
Dim n2 As IXMLDOMElement
Dim blValiderad As Boolean
Const file = "c:\temp\abc.xml"
xDoc.async = False
xDoc.validateOnParse = False
xDoc.resolveExternals = False
xDoc.preserveWhiteSpace = True
Set n0 = xDoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
xDoc.appendChild n0
Set n1 = xDoc.createElement("Document")
n1.setAttribute "xmlns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
n1.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"
Set n2 = xDoc.createNode(NODE_ELEMENT, "CstmrCdtTrfInitn", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03")
n2.Text = "hello"
n1.appendChild n2 'CstmrCdtTrfInitn
xDoc.appendChild n1 'Document
Debug.Print xDoc.XML
关于xml - 为什么这个 XML 属性会引发验证错误,为什么它仍然存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71263504/