Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1175
  • Last Modified:

Select XML node in VB.net

I have

<ImportSession>
  <Batches>
     <Pages>
         <Page filename=C:\uploads\a1.txt />
         <Page filename=C:\uploads\b1.txt />      
     </Pages>
   </Batches>
</ImportSession>

Using VB.Net how can I select the Pages node and add a new page element (<Page filename=C:\uploads\c1.txt />)?

thanks
   tim
0
NESupply
Asked:
NESupply
  • 3
1 Solution
 
Bob LearnedCommented:
Imports System.Xml

  Public Sub AddPage(ByVal xmlFileName As String, ByVal pageFileName As String)

    Dim doc As New XmlDocument
    doc.Load(xmlFileName)

    Dim pages As XmlNode = doc.SelectSingleNode("//Pages")

    Dim newPage As XmlElement = doc.CreateElement("Page")
    Dim attribFileName As XmlAttribute = doc.CreateAttribute("filename")
    attribFileName.Value = pageFileName
    newPage.Attributes.Append(attribFileName)

    pages.AppendChild(newPage)

    doc.Save(xmlFileName)

  End Sub

Sample usage:
   AddPage("c:\temp\test.xml", "c:\test\test.01")

Bob
0
 
Bob LearnedCommented:
Note:

You need quotes for the 'filename' attributes that you have shown:

<ImportSession>
  <Batches>
     <Pages>
         <Page filename="C:\uploads\a1.txt" />
         <Page filename="C:\uploads\b1.txt" />      
     </Pages>
   </Batches>
</ImportSession>

Bob
0
 
NESupplyAuthor Commented:
Dim pages As XmlNode = doc.SelectSingleNode("//Pages")

What is the // before Pages?

thanks
   tim
0
 
Bob LearnedCommented:
If you look at XPath syntax, the '//' means, looks for <Pages> element anywhere within the document.  It is a short-cut expression instead of having to select nodes like this:

  ImportSession/Batches/Pages

Bob
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now