Insert a new entry in XML
I have an XML below like this and I want to add in another entry to it:
<?xml version="1.0" encoding="utf-8"?>
<CampaignRewardsVoucher>
<VoucherCode>Vouch001</VoucherCode>
<Quantity>3</Quantity>
</CampaignRewardsVoucher>
I have the above xml but I want to add Vouch002 after Vouch001:
<VoucherCode>Vouch002</VoucherCode>
<Quantity>3</Quantity>
</CampaignRewardsVoucher>
I have the code below which checks if an input is a duplicate and update accordingly, if not I want to create a new Vouch002 entry, please advice, thanks:
'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.WriteEle开发者_如何学PythonmentString("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
You can add a new child node at the desired position using 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
'...
精彩评论