XML manipulation in VB.NET

opeca

Member
Joined
Mar 3, 2007
Messages
7
Programming Experience
1-3
Hi All,

I've red many pages in connection with the above "problem", but cannot find any useable information.

My problem, that I have an little XML, like:

HTML:
<DB>
 
<Data>
<Name>X</Name>
<Place>BX</Place>
</Data>
 
<Data>
<Name>Y</Name>
<Place>BY</Place>
</Data>
 
</DB>
As I suppose, it's something "Multi element" XML.

How can I read node names and its values from it?


Thanks
 
I usually prefer XmlDocument, find it easy to make selections with XPATH queries and it allows to modify the Xml data. Example:
VB.NET:
Sub xmlread1()
    Dim xdoc As New Xml.XmlDocument
    xdoc.Load("db.xml")
    Dim nodes As Xml.XmlNodeList = xdoc.SelectNodes("/DB/Data")
    For Each node As Xml.XmlNode In nodes
        Dim name As Xml.XmlNode = node.SelectSingleNode("Name")
        Dim place As Xml.XmlNode = node.SelectSingleNode("Place")
        MsgBox(name.InnerText & " " & place.InnerText)
    Next
End Sub
You can also use a XmlTextReader to read the document. Example:
VB.NET:
Class BO
    Public name, place As String
End Class
Sub xmlread2()
    Dim l As New List(Of BO)
    Dim BOx As BO = Nothing
    Dim xr As New Xml.XmlTextReader("db.xml")
    Do While xr.Read
        If xr.NodeType = Xml.XmlNodeType.Element Then
            Select Case xr.Name
                Case "Data"
                    BOx = New BO
                Case "Name"
                    BOx.name = xr.ReadElementContentAsString
                Case "Place"
                    BOx.place = xr.ReadElementContentAsString
                    l.Add(BOx)
                    MsgBox(BOx.name & " " & BOx.place)
            End Select
        End If
    Loop
    xr.Close()
End Sub
 
The xml data you posted worked fine and did only have one root element, which was "DB" node. I used exactly what you posted.
 
BTW, I have one more very common way of handling Xml I should tell about, that is using serialization and class objects. When you have a ready Xml input as posted you can use the Xsd.exe utility to generate schema file, which with same Xsd.exe can generate VB.Net classes from that schema. The commands where xml data is saved as "db.xml" is: (using Visual Studio command prompt)
VB.NET:
xsd db.xml
xsd /c /l:vb db.xsd
Now you can Add Existing to include the generated "db.vb" class file. These two simple methods provide serialization and deserialization of the data:
VB.NET:
Sub xmlserialize(ByVal ldb As DB)
    Dim ser As New Xml.Serialization.XmlSerializer(GetType(DB))
    Using fs As New IO.FileStream("db.xml", FileMode.Create, FileAccess.Write)
        ser.Serialize(fs, ldb)
    End Using
End Sub
 
Function xmldeserialize() As DB
    Dim ser As New Xml.Serialization.XmlSerializer(GetType(DB))
    Using fs As New IO.FileStream("db.xml", FileMode.Open, FileAccess.Read)
        xmldeserialize = ser.Deserialize(fs)
    End Using
End Function
Usage of this is easy, here is an example that reads the data, displays and modifies it, then writes it back to file:
VB.NET:
Sub xmlreadwriteSER()
    Dim ldb As DB = xmldeserialize()
    For Each item As DBData In ldb.Items
        MsgBox(item.Name & " " & item.Place)
        item.Place = "new place"
    Next
    xmlserialize(ldb)
End Sub
The other way around, starting by defining and populating class instances in code and serializing them to file is basically the same, but you have to remember to mark your classes with the Serializable attribute.
 
Thank you JohnH for the correct answer - it's working already -, and for the useful advices!

Have a nice day!
 
Hi JohnH,

I would like to ask another question:

How can I add a node to a specify region?

I try this one, but in this case, the node has created in the first region. . .:

VB.NET:
Dim elem As XmlElement = xdoc.CreateElement("Birth")
elem.InnerText = "1978"
Dim root As XmlNode = xdoc.DocumentElement.SelectSingleNode("/DB/Data")
root.AppendChild(elem)
But if I would like to insert node to the second Data region, what should I do? Like:

<DB>

<Data>
<Name>X</Name>
<Place>BX</Place>
</Data>

<Data>
<Name>Y</Name>
<Place>BY</Place>
<Birth>1978</Birth>
</Data>

</DB>
Thanks
 
You see the first example selects /DB/Data as nodelist, it consist of all Data nodes of DB node. Example here appends to second item in that nodes collection:
VB.NET:
Dim xdoc As New Xml.XmlDocument
xdoc.Load("db.xml")
Dim nodes As Xml.XmlNodeList = xdoc.SelectNodes("/DB/Data")
Dim elem As Xml.XmlElement = xdoc.CreateElement("Birth")
elem.InnerText = "1978"
nodes(1).AppendChild(elem)
xdoc.Save("db.xml")
XmlDocument is nice in these cases where you get a document and modify some node(s). To generate a full Xml file from composite data you may have in application often XmlTextWriter is better. Serialization is not good when the class structure change, just for comparison of methods.. :) But you could have defined the Birth member here in schema initially if you at design time knew and wanted to make room for it, even if there was no birth data yet, and this would then be a part of the class structure. This is called planning or data design ;)
 
Oh, Thank you for the quick reply...

It's clear now.

My last question - for today:) - that how can I modify the specify InnerText?

I've made a simple method:

VB.NET:
If Place.InnerText = "BX" Then
         Place.InnerText = "BX_Modified"
         xdoc.Save("C:\db.xml")
End If
...but I think, it must be a more professional way for it.
 
BTW, I think XML is very good, for the tree-structure, not so huge databases, but in VB.Net there is no any simple method to manipulte its data...

I don't know, why.
 
VB.NET:
If Place.InnerText = "BX" Then          Place.InnerText = "BX_Modified"
...but I think, it must be a more professional way for it.
Anything can't done simpler than that? (if value = x then value = y) I don't see how that is "unprofessional". You only need to save after doing all modifications, not for every single change.
BTW, I think XML is very good, for the tree-structure, not so huge databases, but in VB.Net there is no any simple method to manipulte its data...

I don't know, why.
Think of Xml as a well structured "document", not a database, even if Xml can be used for small local databasing needs.

I find the VB.Net methods to handle Xml are easy, it's probably just much new for you now, new Xml format, new XPATH query language and new VB.Net classes and methods you're not familiar with yet.. I can recommend the XML and XPATH tutorials at W3 Schools.
 
Back
Top