我发现了一些似乎围绕着我想做的事情跳舞的项目。我不是一个成熟的程序员,但一直在 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 - 这是一个 xpath 示例和具有第二次地址迭代的示例输出:
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>