I have a macro in Excel that reads XML information from one file and duplicates them in another. Since the second file has more and different information and user input determines what is being mapped, I am unable to simply copy files. The user chooses which genres to copy from source to target, for instance, using the traditional example of a movie database. I have a spreadsheet with the XPaths for the source and target, and I need to map particular variables across. Not all of the tags are present in the new XML file, therefore before their values can be entered, they must be produced by my code.
I've got a great start from Greg-R's work at Create xml file based on xPath from Excel with VBA ; but his code doesn't handle numbered nodes. I've easily stripped the number from the target tag, but can't figure out the correct methods for adding the attribute to the node. E.g. the XPath could be //Movies/Title[@number=1]/Actor[@number=5].Name
Here's what I've got so far:
Sub makeXPath(xmldoc As Object, xpath As String)
'Original code from: https://example.com/questions/12149941/create-xml-file-based-on-xpath-from-excel-with-vba
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
Debug.Print "partsOfPath(" & i & ") = " & partsOfPath(i)
NumberPos = InStr(partsOfPath(i), "[@number=")
If NumberPos > 0 Then
'Numbered node, extract the number
ElementName = Left(partsOfPath(i), NumberPos - 1)
'Len("[@number=") = 9. Speed the code up by not calculating it each time. Every little bit helps!
NodeNumber = Mid(partsOfPath(i), NumberPos + 9, Len(partsOfPath(i)) - NumberPos - 9)
Else
ElementName = partsOfPath(i)
NodeNumber = ""
End If
Set objMemberElem = xmldoc.createElement(ElementName)
objParent.appendChild objMemberElem
If Not NodeNumber = "" Then
objMemberElem.createAttribute ("number") '<<<------ This bit is throwing errors :(
.createAttribute ("number")
objParent.Attributes.setNamedItem(objAttr).Text = NodeNumber
End If
'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
I've researched this til I'm blind (How many tabs can Chrome handle?) and tried various methods, but none are working. What are the methods I should be using?