PDA

Click to See Complete Forum and Search --> : VB.NET: Append string to Xml file


toytoy
Sep 2nd, 2004, 08:29 PM
Hi

Say i receive one string full of Xml tags ...

Example: "<Person>John</Person><Item>Pen</Item><Amount>4</Amount>"


How to save and append these tags to my xml files..

They told me to use appendChild method.. maybe i am not quite sure with string....... i save the string two times instead..
I am using VB.NET....

Dim myDoc As New Xml.XmlDocument
Dim myXml As String
myXml = "<Person>John</Person><Item>Pen</Item> _
<Amount>4</Amount>

myDoc.LoadXml(myXml)

Dim root As XmlNode = myDoc.DocumentElement

Dim person As XmlElement = myDoc.CreateElement("Person")
person.InnerText = John

Dim itemy As XmlElement = myDoc.CreateElement("Item")
item.InnerText = pen

Dim amount As XmlElement = myDoc.CreateElement("Amount")
amount.InnerText = 4

root.AppendChild(person)
root.AppendChild(item)
root.AppendChild(amount)
myDoc.Save("1.xml")

How to solve this so that it will append to the xml whenever i receive a string...

Thanks.

mendhak
Sep 3rd, 2004, 12:32 AM
Are you adding a new node?

See if this helps:



Sub NewNodeInXMLFile(ByVal strPath As String, ByVal strGender As String, ByVal strFirstName As String, ByVal strLastName As String)
Dim XMLd As New XmlDocument
Dim XMLN As XmlNode


'and xmldocument, to represent the instance of the XML file we're dealing with.
XMLd.Load(strPath)

'An XML Element <name>
Dim xmlEl As XmlElement = XMLd.CreateElement("name")
'It can have an attribute gender=...>
Dim xmlAttr As XmlAttribute = XMLd.CreateAttribute("gender")
'gender="male">
xmlAttr.Value = strGender



' now we have <name gender="male">
xmlEl.Attributes.Append(xmlAttr)
'one more attribute, for old times sake...
xmlAttr = XMLd.CreateAttribute("moron")
xmlAttr.Value = "True"
'now, we add the attribute to the element. Again.
xmlEl.Attributes.Append(xmlAttr)

'What goes INside the element we just made.
xmlEl.InnerXml = "<firstname></firstname><lastname></lastname>"




'give it some values
xmlEl.Item("firstname").InnerText = strFirstName
xmlEl.Item("lastname").InnerText = strLastName


'append the whole element to the whole damn document.
XMLd.DocumentElement.AppendChild(xmlEl)
'save the document now!
XMLd.Save(Server.MapPath("family.xml"))


'navigation
'delete node

End Sub