无法插入以下XML节点VB.net

时间:2019-06-18 20:10:06

标签: xml vb.net append child-nodes

我想附加以下XML文件以包含其他<ID>Sam</ID>

<INDEX>
  <ID>Billy</ID>
</INDEX>

但是我似乎无法使其正常工作,我尝试的是以下代码。

Dim NEWNAME as string="SAM"
Dim xmlIndex As XmlDocument = New XmlDocument()
xmlIndex.Load(Application.StartupPath & "\SYSTEM\MY_INDEX.xml")

With 
xmlDoc.SelectSingleNode("/INDEX").CreateNavigator().AppendChild()
.WriteStartElement("ID", NEWNAME)                                                                  
.WriteEndElement()
.Close()

xmlIndex.Save(Application.StartupPath & "\SYSTEM\MY_INDEX.xml")

End With

也请注意,为方便起见,我已将NEWNAME声明为等于SAM,但这也可以是TextBox.Text

1 个答案:

答案 0 :(得分:0)

我通常用这样的东西来写一个新的节点。

Dim NEWNAME As String = "SAM"
Dim xmlIndex As XmlDocument = New XmlDocument()
xmlIndex.Load("C:\Test.xml")

Dim root As XmlNode = xmlIndex.DocumentElement
Dim elem As XmlElement = xmlIndex.CreateElement("ID")
elem.InnerText = NEWNAME
root.AppendChild(elem)

xmlIndex.Save("C:\Test.xml")