im usin" DOMDocument60"使用VB6,我需要生成一个XML文件,但是我在尝试添加" Attibutes"时遇到了问题。到一个子节点。 这是生成我的代码的文件:
<myroot>
<MyNode SIZE="10">
<SubNode/>
</MyNode>
</myroot>
这就是我需要的:
<myroot>
<MyNode SIZE="10">
**<SubNode CODE="0000" ID="XXX" OTHER="XXX"/>**
</MyNode>
</myroot>
这是代码(基于http://msdn.microsoft.com/en-us/library/ms760231%28v=vs.85%29.aspx):
私人功能CrearDOM() 昏暗的dom 设置dom = New DOMDocument60 dom.async = False dom.validateOnParse = False dom.resolveExternals = False dom.preserveWhiteSpace = True 设置CrearDOM = dom 结束功能
Public Sub Crear_XML()
Set dom = CrearDOM
' Encabezado de XML
Set node = dom.createProcessingInstruction("xml", "version='1.0' encoding='iso-8859-1'")
dom.appendChild node
Set node = Nothing
Dim MyRoot
Set MyRoot = dom.createElement("MasRequest")
MyRoot.appendChild dom.createTextNode(vbNewLine + vbTab)
Set node = dom.createElement("MyNode")
Set attr = dom.createAttribute("SIZE")
attr.Value = 10
node.setAttributeNode attr
Set attr = Nothing
Set Nodo_Sub = dom.createDocumentFragment
Nodo_Sub.appendChild dom.createTextNode(vbNewLine + vbTab + vbTab)
Nodo_Sub.appendChild dom.createElement("SubNode")
node.appendChild Nodo_Droga
MyRoot.appendChild node
End Sub
感谢您的帮助。
答案 0 :(得分:2)
您的问题是您在创建子节点后没有向子节点添加任何属性。我根据你的代码编写了一个例子,但我改变了一些只是因为我习惯这样做。
Private Function CrearDOM()
Dim dom As DOMDocument60
Set dom = New DOMDocument60
With dom
.async = False
.validateOnParse = False
.resolveExternals = False
.preserveWhiteSpace = True
End With
Set CrearDOM = dom
End Function
Public Sub Crear_XML()
Dim dom As DOMDocument60
Dim MyRoot As IXMLDOMNode
Dim node
Dim childNode As IXMLDOMNode
Dim attr
Set dom = New DOMDocument60
With dom
.async = False
.validateOnParse = False
.resolveExternals = False
.preserveWhiteSpace = True
End With
Set node = dom.createProcessingInstruction("xml", "version='1.0' encoding='iso-8859-1'")
dom.appendChild node
Set node = Nothing
Set MyRoot = dom.createElement("MasRequest")
MyRoot.appendChild dom.createTextNode(vbNewLine + vbTab)
Set node = dom.createElement("MyNode")
Set attr = dom.createAttribute("SIZE")
attr.Value = 10
node.setAttributeNode attr
Set attr = Nothing
'create the child node'
Set childNode = dom.createElement("SubNode")
Set attr = dom.createAttribute("CODE")
attr.Value = "0000"
childNode.Attributes.setNamedItem attr
Set attr = dom.createAttribute("ID")
attr.Value = "XXX"
childNode.Attributes.setNamedItem attr
Set attr = dom.createAttribute("OTHER")
attr.Value = "XXX"
childNode.Attributes.setNamedItem attr
node.appendChild childNode
MyRoot.appendChild node
dom.appendChild MyRoot
End Sub
上面的代码为我生成了这个。 (我添加了换行和缩进。)
<?xml version="1.0"?>
<MasRequest>
<MyNode SIZE="10">
<SubNode CODE="0000" ID="XXX" OTHER="XXX"/>
</MyNode>
</MasRequest>