如何更新xml中的节点?

时间:2014-12-17 16:25:45

标签: xml vb.net

我想使用xml更新vb.net中的节点,但我找不到合适的解决方案。

这就是我的阅读和写作:

  If (IO.File.Exists(Application.StartupPath & "MyXML.xml")) Then
        Dim document As XmlReader = New XmlTextReader("MyXML.xml")
        While (document.Read())
            Dim type = document.NodeType
            If (type = XmlNodeType.Element) Then
                If (document.Name = "port") Then
                    port = document.ReadInnerXml.ToString()
                End If
            End If
        End While
    Else
        Dim settings As New XmlWriterSettings()
        settings.Indent = True
        Dim XmlWrt As XmlWriter = XmlWriter.Create("MyXML.xml", settings)
        With XmlWrt
            .WriteStartDocument()
            .WriteComment("XML.")
            .WriteStartElement("Data")
            .WriteStartElement("Settings")
            .WriteStartElement("port")
            .WriteString("7008")
            .WriteEndElement()
            .WriteEndDocument()
            .Close()
        End With

    End If

2 个答案:

答案 0 :(得分:3)

这是更新XML节点的一个小小的开始,请参阅下面的示例。您需要根据需要进行一些调整以满足您的需求。您提供的代码仅用于读取和创建XML文件,而不是按照您的指示更新。考虑到这一点,我不确定你正在寻找什么节点(可能是“节点”),但在我的例子中......

  

“YOURNODE” - 将此更改为您要查找的节点

     

“NEW NODES TEXT” - 将此更改为您希望节点的位置(文本)

Dim MyXML As New XmlDocument()
MyXML.Load(Application.StartupPath & "MyXML.xml")
Dim MyXMLNode As XmlNode = MyXML.SelectSingleNode("YOURNODE")

'If we have the node let's change the text
If MyXMLNode IsNot Nothing Then
  MyXMLNode.ChildNodes(0).InnerText = "NEW NODES TEXT"
Else
  'Do whatever 
End If 

'Save the XML now
MyXML.Save(Application.StartupPath & "MyXML.xml")

按您的要求编辑代码

我们必须深入了解子节点,一旦我们拥有它,我们就可以改变那个文本......

  Dim MyXML As New XmlDocument()
    MyXML.Load(Application.StartupPath & "MyXML.xml")
    Dim MyXMLNode As XmlNode = MyXML.SelectSingleNode("Data")

    'If we have the node let's change the text
    If MyXMLNode IsNot Nothing Then
        Dim MyXMLNodes As XmlNodeList
        MyXMLNodes = MyXMLNode.ChildNodes(0).ChildNodes

        'Set the nodes text
        If MyXMLNodes IsNot Nothing Then
            MyXMLNodes.Item(0).InnerText = "NEW NODES TEXT"
        End If

        'Save the XML now
        MyXML.Save(Application.StartupPath & "MyXML.xml")

    End If

答案 1 :(得分:0)

使用Powershell解决方案

假设您需要更改tag2内部的值,该值位于tag1内部:

1)保存以下扩展名为.ps1的代码,例如example.ps1

$xml = [xml](Get-Content .\inputfile.xml)
$xml.tag1.tag2="newvalue"
$xml.Save(".\inputfile.xml")

2)现在将以下代码另存为.bat文件在同一文件夹中,例如editxml.bat

Powershell.exe -File  example.ps1

3)使用

从VB.NET执行此蝙蝠
process.start("editxml.bat")