首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >属性进入所有元素中。

属性进入所有元素中。
EN

Stack Overflow用户
提问于 2019-09-05 19:51:10
回答 1查看 40关注 0票数 1

我正在使用VBA创建一个可供软件读取的XML。问题是,在创建元素时,根元素需要一个属性,但该属性被分配给所有元素,我看不出有什么问题。

我已经查看了MSDN上的各种属性和方法,但找不到我做错了什么

代码语言:javascript
复制
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

上面的代码创建了以下内容:

代码语言:javascript
复制
<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd"> 
   <SpecificationRow xmlns="">
      <Data>Values</Data>
   </SpecificationRow>
</Specification>

但我需要这个:

代码语言:javascript
复制
<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd"> 
   <SpecificationRow>
      <Data>Values</Data>
   </SpecificationRow>
</Specification>

第一个子函数创建元素,第二个子函数从AddChild读取的数组中传递值。然后创建XML。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-05 22:01:47

我认为您混淆了属性和名称空间。document createNode方法允许您创建具有命名空间的元素(type=1)。

下面是一个例子:

代码语言:javascript
复制
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

下面的输出

代码语言:javascript
复制
<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd">
  <SpecificationRow>
    <Data>Values</Data>
  </SpecificationRow>
</SpecificationRow>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57804878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档