我正在使用VBA创建一个可供软件读取的XML。问题是,在创建元素时,根元素需要一个属性,但该属性被分配给所有元素,我看不出有什么问题。
我已经查看了MSDN上的各种属性和方法,但找不到我做错了什么
Private Xdoc As DOMDocument
Private Root As IXMLDOMElement
Private Parents As IXMLDOMElement
Private Att As IXMLDOMAttribute
Private Sub CreateRoot()
Page = "http://tempuri.org/SpecificationImportData.xsd"
Set Xdoc = CreateObject("MSXML2.DOMDocument")
Set Att = Xdoc.createAttribute("xmlns")
Set Root = Xdoc.createElement("Specification")
Set Parents = Xdoc.createElement("SpecificationRow") value
Xdoc.appendChild Root
Att.Value = Page
Root.setAttributeNode Att
End Sub
Sub AddChild(Ary() As String)
Dim I As Integer, Elem As IXMLDOMElement, Page As String
I = 0
For Each E In fDom()
Set Elem = Xdoc.createElement(E)
Elem.Text = Ary(I)
Parents.appendChild Elem
I = I + 1
Next
Root.appendChild Parents
End Sub上面的代码创建了以下内容:
<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd">
<SpecificationRow xmlns="">
<Data>Values</Data>
</SpecificationRow>
</Specification>但我需要这个:
<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd">
<SpecificationRow>
<Data>Values</Data>
</SpecificationRow>
</Specification>第一个子函数创建元素,第二个子函数从AddChild读取的数组中传递值。然后创建XML。
发布于 2019-09-05 22:01:47
我认为您混淆了属性和名称空间。document createNode方法允许您创建具有命名空间的元素(type=1)。
下面是一个例子:
Private Sub CreateRoot()
Dim strNameSpace As String
strNameSpace = "http://tempuri.org/SpecificationImportData.xsd"
Dim xml As Object
Dim ndRoot As Object
Dim ndParent As Object
Dim ndChild As Object
Set xml = CreateObject("MSXML2.DOMDocument")
Set ndRoot = xml.createNode(1, "Specification", strNameSpace)
xml.appendChild ndRoot
Set ndParent = xml.createNode(1, "SpecificationRow", strNameSpace)
ndRoot.appendChild ndParent
Set ndChild = xml.createNode(1, "Data", strNameSpace)
ndParent.appendChild ndChild
ndChild.Text = "Values"
MsgBox xml.xml
End Sub下面的输出
<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd">
<SpecificationRow>
<Data>Values</Data>
</SpecificationRow>
</SpecificationRow>https://stackoverflow.com/questions/57804878
复制相似问题