2016-08-26 153 views
0

我已經使用搜索來測試許多選項,但這裏是另一個選項。從XML中刪除子節點

我的XML文件

<fields> 
    <field> 
    <fieldId>1</fieldId> 
    <fieldName>Reporting Member State</fieldName> 
    <worksheetName>AIF1</worksheetName> 
    <fieldStartLine>7</fieldStartLine> 
    <fieldEndLine>7</fieldEndLine> 
    <fieldStartCol>3</fieldStartCol> 
    <fieldEndCol>13</fieldEndCol> 
    </field> 
    <field> 
    <fieldId>2</fieldId> 
    <fieldName>Version</fieldName> 
    <worksheetName>AIF1</worksheetName> 
    <fieldStartLine>8</fieldStartLine> 
    <fieldEndLine>8</fieldEndLine> 
    <fieldStartCol>3</fieldStartCol> 
    <fieldEndCol>13</fieldEndCol> 
</field> 
<field> 
    <fieldId>3</fieldId> 
    <fieldName>Creation date and time of the file</fieldName> 
    <worksheetName>AIF1</worksheetName> 
    <fieldStartLine>9</fieldStartLine> 
    <fieldEndLine>9</fieldEndLine> 
    <fieldStartCol>3</fieldStartCol> 
    <fieldEndCol>13</fieldEndCol> 
</field> 
</fields> 

我的代碼:

Sub removeXML(fieldId As Integer) 
    Dim found As Boolean 
    found = False 
    Dim strPath As String 
    strPath = ThisWorkbook.Path & "\src\fields.xml" 
    Dim XDoc As Object 
    Set XDoc = CreateObject("MSXML2.DOMDocument") 
    XDoc.async = False 
    XDoc.validateOnParse = False 
    XDoc.Load (strPath) 
    Set xObjDetails = XDoc.ChildNodes(0) 
    Set xObject = xObjDetails.FirstChild 
    For Each xObject In xObjDetails.ChildNodes 

     For Each xChild In xObject.ChildNodes 
      If (xChild.BaseName = "fieldId") And (xChild.Text = fieldId) Then 
       found = True 
      End If 
      If (found) Then 
       xObject.ParentNode.RemoveChild (xObject) 
       XDoc.Save (ThisWorkbook.Path & "\src\fields2.xml") 
       Exit Sub 
      End If 
     Next xChild 
    Next xObject 
End Sub 

的目標是刪除包含指定fieldId整體<field>節點。

希望它對其他人有用。 (Excel 2015)

回答

0

它在當前狀態下工作。看代碼。