在XML中插入新条目

时间:2011-10-13 05:23:13

标签: asp.net xml vb.net

我有一个像这样的XML,我想在其中添加另一个条目:

<?xml version="1.0" encoding="utf-8"?>
<CampaignRewardsVoucher>
  <VoucherCode>Vouch001</VoucherCode>
  <Quantity>3</Quantity>
</CampaignRewardsVoucher>

我有上面的xml,但我想在Vouch001之后添加Vouch002:

  <VoucherCode>Vouch002</VoucherCode>
  <Quantity>3</Quantity>
  </CampaignRewardsVoucher>

我有下面的代码检查输入是否重复并相应更新,如果不是我想创建一个新的Vouch002条目,请建议,谢谢:

'Create XmlWriterSettings
        Dim settings As XmlWriterSettings = New XmlWriterSettings()
        settings.Indent = True

        If (Not File.Exists("D:\CampaignRewardsVoucher.xml")) Then

            'Create XmlWriter
            Using writer As XmlWriter = XmlWriter.Create("D:\CampaignRewardsVoucher.xml", settings)

                'Begin write
                writer.WriteStartDocument()
                writer.WriteStartElement("CampaignRewardsVoucher")
                writer.WriteElementString("VoucherCode", DropDownList1.SelectedValue)
                writer.WriteElementString("Quantity", TextBox1.Text)

                'End write
                writer.WriteEndElement()
                writer.WriteEndDocument()
            End Using

        Else
            ' file already exist, next check if input data already exist            
            Dim myXmlDocument As XmlDocument = New XmlDocument()
            myXmlDocument.Load("D:\CampaignRewardsVoucher.xml")

            Dim myXMLNode As XmlNode = myXmlDocument.SelectSingleNode("CampaignRewardsVoucher")

            If myXMLNode IsNot Nothing And myXMLNode.ChildNodes(0).InnerText = DropDownList1.SelectedValue Then
                myXMLNode.ChildNodes(1).InnerText = TextBox1.Text

                myXmlDocument.Save("D:\CampaignRewardsVoucher.xml")
            Else

                'insert new node                
                'I need to insert Vouch002 here.

            End If

        End If

1 个答案:

答案 0 :(得分:1)

您可以使用XmlNode.InsertAfter

在所需位置添加新的子节点
'...
Else
    Dim root As XmlNode = myXmlDocument.DocumentElement
    Dim vc As XmlElement = myXmlDocument.CreateElement("VoucherCode")
    vc.InnerText = "Vouch002"
    root.InsertAfter(vc, root.FirstChild)
End If
'...