XML没有写入我的文件

时间:2013-12-02 19:04:30

标签: xml vb.net

我有一个xml文件,我正在尝试添加一些数据。编写i的代码正在执行而没有任何错误,但我没有看到任何发生的事情。

XML文件如下所示:

<NewDataSet>
  <Instance>
  ...
  </Instance>
  <Instance>
  ...
  </Instance>
</NewDataSet>

我用

写信给它
            Dim sys_file As New System.Xml.XmlDocument()
            sys_file.Load(SysFilePath)

            With sys_file.SelectSingleNode("/NewDataSet").CreateNavigator().AppendChild()
                .WriteStartElement("Instance")
                .WriteElementString("UID", guid.NewGuid().ToString())
                .WriteEndElement()
            End With


            sys_file.Save(SysFilePath)

2 个答案:

答案 0 :(得分:4)

您必须使用XmlWriter来撰写:

Dim sys_file As New System.Xml.XmlDocument()
sys_file.Load(SysFilePath)

Using xw As System.Xml.XmlWriter = sys_file.SelectSingleNode("/NewDataSet").CreateNavigator().AppendChild()
    With xw
        .WriteStartElement("Instance")
        .WriteElementString("UID", guid.NewGuid().ToString())
        .WriteEndElement()
    End With
End Using

sys_file.Save(SysFilePath)

答案 1 :(得分:0)

alternative approach正在使用CreateElement()AppendChild()

' Create the XmlDocument.
Dim doc as XmlDocument = new XmlDocument()
doc.LoadXml("<NewDataSet><Instance>...</Instance><Instance>...</Instance></NewDataSet>")
' doc.Load(SysFilePath)  ' or load the XML from a file.

' Create a 'UID' element. 
Dim uidElement as XmlElement = doc.CreateElement("UID")
uidElement.InnerText = guid.NewGuid().ToString()

' Create an 'Instance' element.
Dim instanceElement as XmlElement = doc.CreateElement("Instance")

' Append 'UID' to 'Instance'.
instanceElement.AppendChild(uidElement)

' Append 'Instance' to the document.
doc.DocumentElement.AppendChild(instanceElement)

' Save the document to a file. White space is 
' preserved (no white space).
doc.PreserveWhitespace = true
doc.Save(SysFilePath)