Home » excel » excel – Attribute Goes Into All Elements

excel – Attribute Goes Into All Elements

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using VBA to create an XML for a software to read. The problem is when creating the elements, the root element needs an attribute but the attribute is asigned to all elements and I dont see the problem.

I have looked through the various properties and methods on MSDN but can´t find what Im doing wrong

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

The Above code creates this:

<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd"> 
   <SpecificationRow xmlns="">
      <Data>Values</Data>
   </SpecificationRow>
</Specification>

But I need this:

<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd"> 
   <SpecificationRow>
      <Data>Values</Data>
   </SpecificationRow>
</Specification>

The first sub creates the elements and the second sub gets called form a sub that passes values from an array that AddChild reads. It then creates the XML.

How to&Answers:

I think you’re confusing attributes with namespaces. The document createNode method allows you to create an Element (type=1) with a namespace.

Here’s a example:

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

This outputs

<Specification xmlns="http://tempuri.org/SpecificationImportData.xsd">
  <SpecificationRow>
    <Data>Values</Data>
  </SpecificationRow>
</SpecificationRow>