Dynamically append an XML document
This code demonstrates how to append an XML document. We will add a new element and some inner text. Call the function, provide arguments for the path to the file, the name of the child node, the element name, and the text to add. The file is opened, appended, and saved. The function returns a...
This code demonstrates how to append an XML document. We will add a new element and some inner text.
Call the function, provide arguments for the path to the file, the name of the child node, the element name, and the text to add. The file is opened, appended, and saved. The function returns a true if it succeeds and a false if it fails.
This is the before and after of the pageLinks.xml file.
before:
after:http://www.google.com
I'm using the "button 2" click event to call the function...http://www.google.com http://www.yahoo.com
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim myFilePath = _ "C:\pageLinks.xml" Dim mybool As Boolean = saveToXMLDoc("http://yahoo.com", _ myFilePath, "linkList", "link") End SubThe function is called....
Private Function saveToXMLDoc(ByVal textToAdd As String, _ ByVal filePath As String, ByVal xNode As String, _ ByVal addedElement As String) As Boolean Dim success As Boolean Try 'create place for the document in memory and load it with an existing doc Dim xmlLinksDoc As XmlDocument = New XmlDocument xmlLinksDoc.Load(filePath) Dim xmlNavigator As Xml.XPath.XPathNavigator = xmlLinksDoc.CreateNavigator xmlNavigator = xmlNavigator.SelectSingleNode(xNode) 'xNode is the node we are adding a new child to 'example: xmlNavigator = nav.SelectSingleNode("linkList") xmlNavigator.AppendChildElement("", addedElement, "", textToAdd) 'adds the element (addElement) and the text (textToAdd) 'example: xmlNavigator.AppendChildElement("", "textHolder", "", "This is the text that will be added to the 'textHold' node.") xmlLinksDoc.Save(filePath) success = True Catch ex As Exception success = False End Try Return success End Function