替换XML文件中的值

时间:2019-12-18 07:48:11

标签: .net xml vb.net

我正在尝试加载XML文件,替换特定值,然后保存文件。

这是文件的外观:

Version="36"

我正在尝试更新示例中的第四行-使用Dim gzFile As String = "C:\users\desktop\delete.txt" Dim doc As XmlDocument = New XmlDocument Dim xmlReader As XmlTextReader = New XmlTextReader(gzFile) doc.Load(xmlReader) Dim nodes As XmlNodeList = doc.SelectNodes("PremiereData/Project/Project") MsgBox(doc.SelectSingleNode("PremiereData/Project/Project".ToString)) For Each node As XmlNode In nodes MsgBox(node.Attributes("Version").Value.ToString) If node.Attributes("Version").Value.ToString Is "36" Then MsgBox("found") node.Attributes("Version").Value = "16" End If Next xmlReader.Close() doc.Save(gzFile) 。我遇到的问题是36个整数从一个文件更改到另一个文件,并且它可以有任何数字。该文件还包含字符串Version的一些实例。那么如何替换第一个版本?

这是我尝试过的:

class Dog: Object {
    @objc dynamic var name = ""
    let owners = List<Owner>()
}

2 个答案:

答案 0 :(得分:0)

如果要更改具有Version的第一个Project元素的ObjectID='1'属性的值,可以执行以下操作:

Imports System.Xml

Module Module1

    Sub Main()
        Dim src = "C:\temp\project.xml"
        Dim doc As New XmlDocument
        doc.Load(src)

        Dim n = doc.SelectSingleNode("//Project[@ObjectID='1']")
        If n IsNot Nothing Then
            Dim attr = n.SelectSingleNode("@Version")
            If attr IsNot Nothing Then
                attr.Value = "Look here!"
            Else
                ' Perhaps do something if it is a problem there is no "Version" attribute.
            End If
        Else
            ' Perhaps do something if it is a problem there is no Project with ObjectID='1'.
        End If

        doc.Save(src)

        Console.ReadLine()

    End Sub

End Module

结果:

<?xml version="1.0" encoding="UTF-8"?>
<PremiereData Version="3">
  <Project ObjectRef="1" />
  <Project ObjectID="1" ClassID="62ad66dd-0dcd-42da-a660-6d8fbde94876" Version="Look here!">
    <Node Version="1">
      <Properties Version="1">
        <ProjectViewState.List ObjectID="2" ClassID="aab0946f-7a21-4425-8908-fafa2119e30e" Version="3">
          <ProjectViewStates Version="1">
          </ProjectViewStates>
        </ProjectViewState.List>
      </Properties>
    </Node>
  </Project>
</PremiereData>

请注意,属性值是一个字符串,对它的解释将是整数(在您的情况下)。

答案 1 :(得分:0)

尝试一下:

遍历所有节点,检查Node.Attributes ("Value")是否为Not Nothing,然后对它进行任何操作。

Dim gzFile As String = "C:\users\desktop\delete.txt"
Dim doc As XmlDocument = New XmlDocument
Dim xmlReader As XmlTextReader = New XmlTextReader(gzFile)
doc.Load(xmlReader)
Dim nodes As XmlNodeList = doc.SelectNodes("PremiereData/Project")

Dim found As Boolean = False
For Each node As XmlNode In nodes
    If (Not node.Attributes ("Value") Is Nothing) Then
        If (node.Attributes("Version").Value.ToString  = "36" ) Then
            MsgBox("found")
            node.Attributes("Version").Value = "16"
            found = True
        End If
        If found = True
            Exit For
        End If
    End If
Next

xmlReader.Close()
doc.Save(gzFile)