Could you let me know how to loop through an xml file and retrieve the values of the elements and the attributes.
Thanks
Printable View
Could you let me know how to loop through an xml file and retrieve the values of the elements and the attributes.
Thanks
Well, do you want returned as a string?
VB Code:
Dim sb As New System.Text.StringBuilder Dim fs As New System.IO.FileStream("c:\myxml.xml", IO.FileMode.Open) Dim r As New System.Xml.XmlTextReader(fs) While r.Read sb.Append(r.ReadString) End While r.Close() fs.Close() Debug.WriteLine(sb.ToString)
That will give you just the data in the nodes... not the identifying attributes or markup.
this will get you the file copntents
VB Code:
Dim sb As New System.Text.StringBuilder Dim fs As New System.IO.FileStream("c:\myxml.xml", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read) Dim mybytes(fs.Length) As Byte fs.Read(mybytes, 0, mybytes.Length) fs.Close() Dim myEnc As New System.Text.UnicodeEncoding 'byte > string Dim s As String = myEnc.GetString(mybytes) Debug.WriteLine(s.ToString)
You can also use the XMLDocument object:
VB Code:
Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click 'load doc Dim xdoc As New Xml.XmlDocument xdoc.Load("data.xml") 'get something to hold the values Dim sb As New System.Text.StringBuilder 'loop through children and call recursive function to get values For Each node As Xml.XmlNode In xdoc.ChildNodes If node.NodeType = Xml.XmlNodeType.Element Then sb.AppendFormat("{0}{1}", RecursiveGetText(node), ControlChars.NewLine) End If Next 'display result txtXML.Text = sb.ToString End Sub Private Function RecursiveGetText(ByVal node As Xml.XmlNode) As String Dim sb As New System.Text.StringBuilder 'write current node values sb.AppendFormat("{0}:{1}", node.Name, node.InnerText) If Not node.Attributes Is Nothing Then 'write attributes For Each atr As Xml.XmlAttribute In node.Attributes sb.AppendFormat(" @{0}:{1}", atr.Name, atr.Value) Next End If sb.Append(ControlChars.NewLine) 'call recursively to get all generations For Each child As Xml.XmlNode In node.ChildNodes If child.NodeType = Xml.XmlNodeType.Element Then sb.Append(RecursiveGetText(child)) End If Next Return sb.ToString End Function
It just depends on what you want to do with the values or how you want to get them. There are lots of choices.