我发现有些东西似乎围绕着我想做的事情跳舞。我不是一个成熟的程序员,但一直在Excel中创建自己的宏。我正在尝试创建一个,这将帮助我创建XML文件的结构。
对于这个上下文,我有一列Xpath和一个相关的值。我想在XPath列表中找到,并且每个都根据需要在路径中创建任何父项以及子项及其值。我将添加另一个方面来过滤它到我想要的字段,但我正在努力的部分是检查每个父节点是否存在的逻辑,如果需要创建它,然后添加子及其值。
如果输出文件是使用新行上的每个节点进行格式化的话,那么会更好,如果子节点是从父节点缩进的话,那么更多,但只是创建它是我的主要关注点。任何帮助都会非常感激,这有可能为我节省很多时间。
更新: 我在这方面取得了进展,并且能够创建一个小样本文件。我仍然不确定是否有办法使用换行符和/或制表符缩进来格式化文件,但我认为创建文件的主要部分正在进行中。我仍然需要看看如何处理迭代节点。这是我到目前为止,如果有人有任何批评,欢迎:
Sub main()
Dim xmldoc As New DOMDocument60
Dim xpath As String
Dim outPath As String
outPath = "c:\temp\test.xml"
'just a small sample for now, xpaths in column 2 on spreadsheet
For i = 2 To 5
'xpaths I have leave off root element, so I add it here
xpath = "session/" & Cells(i, 2).Value
Call makeXPath(xmldoc, xpath)
Next
xmldoc.Save outPath
End Sub
Private Sub makeXPath(xmldoc As DOMDocument60, xpath As String)
Dim partsOfPath() As String
Dim oNodeList As IXMLDOMNodeList
Dim strXPathQuery As String
Dim sParent As String
Dim objRootElem As IXMLDOMElement
Dim objMemberElem As IXMLDOMElement
Dim objMemberName As IXMLDOMElement
Dim objParent As Object
Set objParent = xmldoc
partsOfPath = Split(xpath, "/")
For i = LBound(partsOfPath) To UBound(partsOfPath)
If strXPathQuery > "" Then strXPathQuery = strXPathQuery & "/"
strXPathQuery = strXPathQuery & partsOfPath(i)
Set oNodeList = xmldoc.SelectNodes(strXPathQuery)
If oNodeList.Length = 0 Then
'if I don't have the node, create it
Set objMemberElem = xmldoc.createElement(partsOfPath(i))
objParent.appendChild objMemberElem
'setting the parent for the next element of the path
Set objParent = objMemberElem
Else
'setting parent to first iteration, until I make adjustment otherwise later
Set objParent = oNodeList.Item(0)
End If
Next
End Sub
Update2 - 以下是xpaths和示例输出的示例,它具有第二次迭代的地址:
data/account/AcctNumber
data/account/Phone
data/account/address/Address1
data/account/address/City
data/account/address/State
data/account/address/ZIP
data/account/address/AddressType
<data>
<account>
<AcctNumber>
<Phone>
<address>
<Address1 />
<City />
<State />
<ZIP />
<AddressType />
</address>
<address>
<Address1 />
<City />
<State />
<ZIP />
<AddressType />
</address>
</account>
</data>