Determine if XML node exists using VB.NET

Posted on 2009-04-27
Last Modified: 2013-11-08
I have an existing XML file that i need to write values to.  How can I determine if a specific node already exists in the file?   If the node does not exist how can i create just one specific node with affecting the entire xml document?
Question by:Mike_Stevens
    LVL 53

    Expert Comment

    you can loop through the attributes on the node if there are attributes present

    If (yourNode.Attributes.Count>0) Then
           For atrib As Integer = 0 To yourNode.Attributes.Count
                If (yourNode.Attributes(atrib).Name = "FieldName") Then
                    'found it
                    x = yourNode.Attributes.GetNamedItem("fieldDoesntExist").Value
                    'or  x = yourNode.Attributes(atrib).Value
                    Exit For ' to exit this for if only needed to find this one attribute
                End If
    End If

    Answer from expert tpwells found at
    LVL 53

    Expert Comment

    LVL 4

    Accepted Solution

    Hi Mike,

    Here's a simple solution to your question. I believe.  I created a small application with a text box to search for a specific xml node, a search button,  a add button, and a close button. I created my own test xml file with a few nodes within it. You could use your own xml file for your testing purposes. The provided code will search for a "specific" node within your file and return you a message. If the message return "...node does not exist." Then you could add the non-existing node name by clicking the add button that's in the search text box. Be aware of case sensitive searches. Your file could contain a node that you are searching within the search text box. I didn't write code for case sensitive checks.

    If a node does exist from your search you will receive a message saying "...node does exist".  Then you could continue your search. If the node doesn't  exist, by clicking on the add button, it will append the text (only one node will be appended) from the search text box to your xml file automatically. So, be sure that the node doesn't already exist in your xml file, before clicking add. The search will find it if, it's typed in the text box correctly.

    I hope this is some help to your question and need. :- )

    Here is my code:

        Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
            '-- Call does node exist method
        End Sub
        Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
            '-- Call insert one new node method.
        End Sub
    Private Sub DoesNodeExist()
            '-- Declare local variable
            Dim mDoc As New XmlDocument()
            '-- Load the actual xml file
            '-- See if the node exist - input a name in the textbox to     search.
            If mDoc.GetElementsByTagName(txtSearch.Text).Count > 0 Then
                MessageBox.Show(txtSearch.Text & " node does exist.", "Node Info...", MessageBoxButtons.OK, MessageBoxIcon.Information)
                '-- XML Node doesn't exist
                MessageBox.Show(txtSearch.Text & " node does not exist.", "Node Info...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
        End Sub
    Private Sub InsertOneNewNode()
                '-- Declare local variable
                Dim doc As New XmlDocument()
                doc.Load("C:\Documents and Settings\Larry\My Documents\book.xml")
                '-- Create a new node and add it to the document.
                Dim NewNode As XmlElement = doc.CreateElement(txtSearch.Text)  '<-- create new node from 
                NewNode.InnerText = "Put your own info here?"
                '-- Append the new node at the end of the file.
                '-- Save the xml file with the new changes.
                '-- Message shows that the changes has been made.
                MessageBox.Show("New xml node has been added.", "XML Node Add...", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Catch ex As Exception
                MessageBox.Show("Make sure there are no 'spaces' or any other non xml node syntax in the text box.", "Invalid xml node...", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub

    Open in new window


    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK ( for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
    If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    This video discusses moving either the default database or any database to a new volume.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now