我们有一个工具可用于自动更新XML文件中的变量。我正在尝试创建一个可以更改这些变量的新工具。我找到了替换节点的方法,但我找不到在特定名称下更改ReplaceWith值的方法。例如,将$ VariableThree替换为值20。
<Variables>
<Variable>
<Name>$VariableOne</Name>
<ReplaceWith>10</ReplaceWith>
</Variable>
<Variable>
<Name>$VariableTwo</Name>
<ReplaceWith>Name</ReplaceWith>
</Variable>
<Variable>
<Name>$VariableThree</Name>
<ReplaceWith>10</ReplaceWith>
</Variable>
Private Sub UpdateAttribute(ByVal FileName As String,ByVal attrValue As String,ByVal NewValue As String)
Dim configXml = New XmlDocument
Dim attr As XmlAttribute
configXml.Load(FileName)
attr = configXml.SelectSingleNode("/configuration/appSettings/add[@Name = '" & attrValue & "']/@value")
attr.Value = NewValue
configXml.Save(FileName)
End Sub
FileName = XML Location
attValue = Name of the Attribute
NewValue = the newer value
答案 0 :(得分:0)
如果您想更新确切的ReplaceWith
值,请尝试以下代码
'Load xml fle
Dim _xdoc As XElement = XElement.Load(_filepath$)
'get the element where name like $VariableThree
Dim _elmnt As XElement = (From s In _xdoc.Descendants("Variable")
Where s.Element("Name") = "$VariableThree"
Select s).FirstOrDefault()
'update the Replacewith value
_elmnt.Element("ReplaceWith").SetValue(200)
'UPDATE CODE here
'update and save xml file
_xdoc.Save(_filepath$)
答案 1 :(得分:0)
这是您的XML文件
<?xml version="1.0" encoding="utf-8"?>
<Variables>
<Variable>
<Name>$VariableOne</Name>
<ReplaceWith>10</ReplaceWith>
</Variable>
<Variable>
<Name>$VariableTwo</Name>
<ReplaceWith>Name</ReplaceWith>
</Variable>
<Variable>
<Name>$VariableThree</Name>
<ReplaceWith>500</ReplaceWith>
</Variable>
</Variables>
我现在只是测试,它工作正常。请复制上面的文字并创建一个新的xml文件然后尝试下面的代码。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _filepath$ = "D:\text.xml"
'Load xml fle
Dim _xdoc As XElement = XElement.Load(_filepath$)
'get the element where name like $VariableThree
Dim _elmnt As XElement = (From s In _xdoc.Descendants("Variable")
Where s.Element("Name") = "$VariableThree"
Select s).FirstOrDefault()
'update the Replacewith value
_elmnt.Element("ReplaceWith").SetValue(500)
'UPDATE CODE here
'update and save xml file
_xdoc.Save(_filepath$)
End Sub