gpt4 book ai didi

excel - 属性进入所有元素

转载 作者:行者123 更新时间:2023-12-04 22:26:04 24 4
gpt4 key购买 nike

我正在使用 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>

第一个 sub 创建元素,第二个 sub 被调用形成一个 sub,它从 AddChild 读取的数组中传递值。然后它创建 XML。

最佳答案

我认为您将属性与 namespace 混淆了。文件createNode方法允许您使用命名空间创建一个元素(类型=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>

关于excel - 属性进入所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57804878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com