An easy way to read/get/retrieve data from XML file by specified element/node/field name in .NET

Posted by Admin L in .NET Programming, Web Programming & Resources on 29-09-2011. Tags:

Author: Nosa Lee
Original Address: https://www.seeksunslowly.com/vb2008-dot-net-read-xml-data-by-element-field-node-name
To reprint this article, please indicate the source, thank you.
_____________________________________

Today, I first need to read data from XML file, think about file format, I feel it can be retrieved by specified element (in fact, that is field or node) name directly, as easy like read from ini configuration file.

But through searched MSDN examples and the related information in the Internet, I found the methods that provide by the skill are very complex. Such as recursive listing all nodes, and then Select Case by node name… Used many class in System.Xml namespace… All these, make the confused for me, it is very different than my thinking.

So, I need to observe all members of XmlDocument class, XML data format is so popular, .NET should has an easy solution for reading XML data.

At last, the key to solve the problem focuses on XmlElement’s Item property. This property can be called with element name parameter, and return a XmlElement object, it can solve this problem like reading ini file.

The simple XML file and Visual Basic 2008 code as below, if you have advanced requirement, please extend it by yourself.
VB2008 code:
[cc lang=”vbnet”]
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
” Declare and initialize XmlDocument object – xd.
Dim xd As New XmlDocument
xd.Load(“H:\test.xml”)

‘ Declare and get the root node/element, please note the usage of Item() property.
Dim xeRoot As XmlElement = xd.Item(“XML_DIZ_INFO”)

‘ Declare XmlElement object – xe and get its reference.
Dim xe As XmlElement = xeRoot.Item(“First_Node”)

” Display each field/element data under the first node.
MsgBox(xe.Item(“Element_1_First”).InnerText)
MsgBox(xe.Item(“Element_2_First”).InnerText)

” Display each field/element data under the second node.
xe = xeRoot.Item(“Second_Node”)
MsgBox(xe.Item(“Element_1_Second”).InnerText)
MsgBox(xe.Item(“Element_2_Second”).InnerText)

End Sub
End Class
[/cc]

Is not very simple? so easy almost than reading from ini file (because only a main parameter).

The referred XML file H:\test.xml as below:
[cc lang=”xml”]



Element_1_First’s data.
Element_2_First’s data.


Element_1_Second’s data.
Element_2_Second’s data.


[/cc]

Of course, above method and idea also can be referred in Web programming or other programming languages.

【赞赏 / Reward】

微信         支付宝         PayPal

Post a comment