将数据附加到现有XML文件

时间:2013-05-31 14:00:30

标签: xml vb.net visual-studio-2008

这是我将新记录附加到现有XML文档的代码:

Sub addEXISTING(ByVal c_name As String, ByVal c_age As Integer, ByVal c_sex As String)
     Dim e_client = doc.CreateElement("CLIENT")

     Dim e_name As Xml.XmlElement = doc.CreateElement("NAME")

     Dim e_age As Xml.XmlElement = doc.CreateElement("AGE")

     Dim e_sex As Xml.XmlElement = doc.CreateElement("SEX")

     e_name.InnerText = c_name
     e_age.InnerText = c_age
     e_sex.InnerText = c_sex
     e_client.AppendChild(e_name)
     e_client.AppendChild(e_age)
     e_client.AppendChild(e_sex)
     childparent.AppendChild(e_client)

     doc.AppendChild(childparent)
     doc.Save("D:\mefolder\me.xml")
     MsgBox("XML DOCUMENT UPDATED!", MsgBoxStyle.Information, "Notice:")
End Sub

但是当执行这段代码时,新数据的文件条目会覆盖现有的代码。

基本上,我想要的输出是这样的(例如(在浏览器中查看XML文档时):

<BIO_INFO>
<CLIENT>   ----- EXISTING 
<NAME>John</NAME> 
<AGE>21</AGE>
<SEX>MALE</SEX>
</CLIENT>
<CLIENT>  ----- NEW ENTRY
<NAME>Elena</NAME>
<AGE>21</AGE>
<SEX>FEMALE</SEX>
</CLIENT>
</BIO_INFO>

但这就是我得到的:

<BIO_INFO>
<CLIENT>
<NAME>Elena</NAME>
<AGE>21</AGE>
<SEX>FEMALE</SEX>
</CLIENT>
</BIO_INFO>"

以下是我的声明:

Dim filer As DirectoryInfo = New DirectoryInfo("D:\mefolder")
Dim doc As New XmlDocument
Dim root As XmlElement = doc.CreateElement("CLIENT")
Dim childparent As XmlElement = doc.CreateElement("BIO_INFO")
Dim child As XmlElement = doc.CreateElement("NAME")
Dim childage As XmlElement = doc.CreateElement("AGE")
Dim childsex As XmlElement = doc.CreateElement("SEX")

1 个答案:

答案 0 :(得分:0)

无法将数据附加到xml文档。您需要加载整个文档并再次保存(来自nianios comment Appending an existing XML file)。有必要使用XmlDocument.Load Method

Sub addEXISTING(ByVal c_name As String, ByVal c_age As Integer, ByVal c_sex As String)

    XmlDocument.Load("D:\mefolder\me.xml")'!

   Dim e_client = doc.CreateElement("CLIENT")
   Dim e_name As Xml.XmlElement = doc.CreateElement("NAME")
   Dim e_age As Xml.XmlElement = doc.CreateElement("AGE")
   Dim e_sex As Xml.XmlElement = doc.CreateElement("SEX")

   e_name.InnerText = c_name
   e_age.InnerText = c_age
   e_sex.InnerText = c_sex
   e_client.AppendChild(e_name)
   e_client.AppendChild(e_age)
   e_client.AppendChild(e_sex)
   childparent.AppendChild(e_client)

   doc.AppendChild(childparent)
   doc.Save("D:\mefolder\me.xml")
  MsgBox("XML DOCUMENT UPDATED!", MsgBoxStyle.Information, "Notice:")
End Sub

请注意,每个记录的打开和保存效率都不高,尤其是当文档很大时。考虑从您的方法中取出.Save.Load并单独触发它们(就像您在文本编辑器中处理文本文件一样)。