如何使用VB.NET编辑XML文件

时间:2015-10-06 12:50:50

标签: xml vb.net

这是XML文件和我的代码。我需要更改<Value>标记中的数字2509。下面的代码找到<Value>SchoolFiles</Value>,但之后跳出循环。我知道循环有一个更好的方法。

XML文件

<Filters>
    <Filter>
        <Name>ViewFolders</Name>
        <ApplyToFiles>0</ApplyToFiles>
        <ApplyToDirs>1</ApplyToDirs>
        <MatchType>None</MatchType>
        <MatchCase>0</MatchCase>
        <Conditions>
            <Condition>
                <Type>0</Type>
                <Condition>0</Condition>
                <Value>SchoolFiles</Value>
            </Condition>
            <Condition>
                <Type>0</Type>
                <Condition>0</Condition>
                <Value>DataImportFiles</Value>
            </Condition>
            <Condition>
                <Type>0</Type>
                <Condition>0</Condition>
                <Value>2509</Value>
            </Condition>
        </Conditions>
    </Filter>
</Filters>
Dim FileZillaXMLFilterFile As String = "C:\Users\Development\AppData\Roaming\FileZilla\filters.xml"
Dim myXmlDocument As XmlDocument = New XmlDocument()
myXmlDocument.Load(FileZillaXMLFilterFile)
Dim MyNode As XmlNode
Dim node As XmlNode
node = myXmlDocument.SelectSingleNode("//Filters")
'node = myXmlDocument.SelectSingleNode("//Filters/Filter/Conditions/Condition/Value")
For Each book As XmlNode In node.ChildNodes

    Debug.Print(book.InnerText) '= Session("iCustID").ToString()
    If Microsoft.VisualBasic.Left(book.InnerText, 11) = "ViewFolders" Then
        For Each node4 As XmlNode In book.ChildNodes
            If node4.Name = "Conditions" Then
                'Debug.Print(node4.LastChild.Name)

                For Each node5 As XmlNode In node4.ChildNodes
                    Debug.Print(node5.Name)
                    For Each node6 As XmlNode In node5.ChildNodes
                        Debug.Print(node6.Name)
                        If node6.Name = "Value" Then
                            Debug.Print(node6.InnerText)
                            For Each node7 As XmlNode In node6.ChildNodes
                                If node7.InnerText <> "SchoolFiles" And node7.InnerText <> "DataImportFiles" Then
                                    'need to change 2509 to another numnber
                                    Debug.Print(node7.InnerText)
                                End If
                            Next
                        End If
                    Next
                Next
            End If
        Next
    End If
Next

1 个答案:

答案 0 :(得分:1)

这样做的诀窍是使用XPath查找正确的节点,然后更改它的值。然后,您可以使用XmlDocument重写该文件。所需节点的XPath是:

/Filters/Filter/Conditions/Condition[Value != 'SchoolFiles' and Value != 'DataImportFiles']/Value

这里我复制了检查SchoolFiles和DataImportFiles的逻辑,但是可能有更好的方法来关注正确的节点。例如,它可能基于它的索引。或者,如果Type节点具有唯一值,则可以使用它。

我在您的代码中看到您已经在使用SelectSingleNode。您可以使用此XPath来节省大量循环。您可以将节点的Value属性设置为新数字,并使用Save方法保存XMLDocument。

像XMLSpy这样的工具对于正确获取XPath非常有用。 W3Schools(http://www.w3schools.com/xml/)是学习XML和XPath的好地方。