2016-10-19 37 views
0

我正在開發一些VBA以獲取一些Excel數據並生成一些XML,然後將這些XML傳遞給SQL過程以供進一步處理。在msxml2中創建內聯XML元素屬性VBA

不幸的是,我有一個問題附加一個xml屬性元素。

我的代碼如下所示:

Private Sub Tester() 

Dim objDom As Object 
Set objDom = CreateObject("msxml2.DOMDocument") 
Set objRootElem = objDom.CreateElement("Allocations") 
objDom.AppendChild objRootElem 

objRootElem.AppendChild(objDom.CreateElement("Employee55")).Text = "Test Element Value" 

MsgBox (objDom.XML) 

End Sub 

這將產生XML,看起來像這樣:

<Allocations><Employee55>Test Element Value</Employee55></Allocations> 

不過我後反對這樣的Employee55元素附加屬性:

<Allocations><Employee55 EmpID="10" EmpDob="01021986">Test Element Value</Employee55></Allocations> 

我知道如果我將Employee對象聲明爲一個對象,並且兩個附加的屬性o bjects,我可以使用Element.SetAttributeNode並傳入Attribute對象。

但在這種情況下,它的動態和我沒有在內存中的元素以這種方式工作。

我正在尋找一種方法來做到這一點,就像我已經將.Text值添加到Employee55元素一樣。

有什麼建議嗎?

感謝,

+0

我不認爲你可以做到這一點在線 - 參與創建和連接太多的操作屬性 –

回答

0

這不是「內聯」,我想,但幾乎沒有一個困難:

Private Sub Tester2() 
    Dim Dom As Object 

    Set Dom = CreateObject("MSXML2.DOMDocument") 
    With Dom 
     With .appendChild(.createElement("Allocations")) 
      With .appendChild(Dom.createElement("Employee55")) 
       .Text = "Test Element Value" 
       .setAttribute "EmpID", "10" 
       .setAttribute "EmpDob", "01021986" 
      End With 
     End With 
     MsgBox .xml 
    End With 
End Sub