vb.net 如何更新xml中的节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27530170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to Update a node in xml?
提问by Danny
I want to update a node in vb.net using xml but I cannot find a proper solution.
我想使用 xml 更新 vb.net 中的节点,但找不到合适的解决方案。
This is what I have for reading and writing:
这是我用于阅读和写作的内容:
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
回答by ???ěxě?
Here's a little start for updating an XML node, please see below for example. You'll need to make a few adjustments as necessary to fit your needs. The code you provided is only for reading and creating an XML file, not updating one as you indicated. With this in mind I'm not sure what node you're looking for (maybe "node"), but in my example...
这是更新 XML 节点的一个小开始,请参见下面的示例。您需要根据需要进行一些调整以满足您的需要。您提供的代码仅用于读取和创建 XML 文件,而不是按照您的指示更新。考虑到这一点,我不确定您正在寻找哪个节点(可能是“节点”),但在我的示例中......
"YOURNODE"- Change this to the node you are looking for
"NEW NODES TEXT"- Change this to what you want the node to be (text)
"YOURNODE"- 将其更改为您要查找的节点
“新节点文本”- 将其更改为您希望节点成为的内容(文本)
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")
Code Edit Per Your Requirements
根据您的要求编辑代码
We have to dig down into the child nodes, once we have it we can change that text...
我们必须深入研究子节点,一旦有了它,我们就可以更改该文本...
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

