无法将子节点附加到父节点(VBA-XML)

时间:2018-05-10 15:22:17

标签: xml vba appendchild

这是我的VBA代码,我正在使用Excel数据表修改XML。 xml在这里:https://www.jiocloud.com/s/?t=SzqFJhEABfsTQfZW&s=a2

function fnUpdateXMLByTags()
Dim mainWorkBook As Workbook
Dim wrsht As Worksheet


Set mainWorkBook = ActiveWorkbook
Set wrsht = mainWorkBook.Sheets("Sheet1")
wrsht.Activate

Dim oXMLFile As MSXML2.DOMDocument60
Set oXMLFile = New MSXML2.DOMDocument60
oXMLFile.async = False
oXMLFile.validateOnParse = False
XMLFileName = "Z:\IPC\IPC1752A_WK-200264-000 - Copy (2).xml"
XmlNamespaces = "xmlns:d='http://webstds.ipc.org/175x/2.0'"
oXMLFile.SetProperty "SelectionNamespaces", XmlNamespaces

For i = 3 To 5
  If Not IsEmpty(mainWorkBook.Sheets("Sheet1").Range("A" & i)) Then

        PartID = mainWorkBook.Sheets("Sheet1").Range("A" & i).Value
        PartName = mainWorkBook.Sheets("Sheet1").Range("B" & i).Value
        MaterialName = mainWorkBook.Sheets("Sheet1").Range("D" & i).Value
        MassAmount = mainWorkBook.Sheets("Sheet1").Range("F" & i).Value
        MassUnit = mainWorkBook.Sheets("Sheet1").Range("G" & i).Value
        Path = "D:\New folder\" & PartID & ".xml"

        If oXMLFile.Load(XMLFileName) Then

            Set PartIDNodes = oXMLFile.SelectNodes("//@itemNumber")
            Set PartNameNodes = oXMLFile.SelectNodes("//@itemName")
            Set MaterialNameNodes = oXMLFile.SelectNodes("//@name")
            Set MassAmountNodes = oXMLFile.SelectNodes("//@value")
            Set MassUnitNodes = oXMLFile.SelectNodes("//@UOM")
            PartIDNodes(0).NodeValue = Part_ID
            PartNameNodes(0).NodeValue = PartName
            MaterialNameNodes(5).NodeValue = MaterialName
            MassAmountNodes(1).NodeValue = MassAmount
            MassUnitNodes(1).NodeValue = MassUnit

        End If

    Else:
        If IsEmpty(mainWorkBook.Sheets("Sheet1").Range("D" & i)) Then
            Substancename = mainWorkBook.Sheets("Sheet1").Range("H" & i).Value
            CASNumber = mainWorkBook.Sheets("Sheet1").Range("I" & i).Value
            SubAmount = mainWorkBook.Sheets("Sheet1").Range("J" & i).Value
           Set SubstanceCategoryNode = oXMLFile.SelectNodes("//d:SubstanceCategory")
           Set Substancenode = oXMLFile.createElement("d:Substance")
           Substancenode.Text = "<SubstanceID identity="" authority=""/> <Amount value="" UOM=""/> "
           SubstanceCategoryNode.appendChild (Substancenode)
             "throwwin error here"

           oXMLFile.Save Path
         End If


End If


Next i

End Function

当我将一个子项附加到父级时,它会抛出“对象不支持此属性或方法”

请建议我错在哪里。还有其他方法可以将子节点附加到父节点

1 个答案:

答案 0 :(得分:1)

答案很简单。而不是

Set SubstanceCategoryNode = oXMLFile.SelectNodes("//d:SubstanceCategory")

我必须使用它。

Set SubstanceCategoryNode = oXMLFile.SelectsingleNode("//d:SubstanceCategory")

从SelectNodes到chooseinglenode。

感谢@qharr和@ThomasMX的支持。