Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Dynamically append an XML document

3.67/5 (3 votes)
23 Mar 2010CPOL 1  
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:
<linklist>
  <link>http://www.google.com</link>
</linklist>

after:
<linklist>
  <link>http://www.google.com</link>
  <link>http://www.yahoo.com</link>
</linklist>


I'm using the "button 2" click event to call the function...
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 Sub


The 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)