Introduction

Parsing XML files has always been time consuming and sometimes tricky. .NET framework provides powerful new ways of parsing XML. The various techniques know to parse xml files with .NET framework are using XmlTextReader, XmlDocument, XmlSerializer, DataSet and XpathDocument. I will explore the XmlTextReader and XmlDocument approach here.

The Xml File

Figure 1 outlines the xml file that will be parsed.

<?xml version="1.0" encoding="UTF-8"?>
<family>
<name gender="Male">
<firstname>Tom</firstname>
<lastname>Smith</lastname>
</name>
<name gender="Female">
<firstname>Dale</firstname>
<lastname>Smith</lastname>
</name>
</family>

Parsing XML with XMLTextReader

Using XmlTextReader is appropriate when the structure of the XML file is relatively simple. Parsing with XmlTextReader gives you a pre .net feel as you sequentially walk through the file using Read() and get data using GetAttribute() andReadElementString() methods. Thus while using XmlTextReader it is up to the developer to keep track where he is in the Xml file and Read() correctly. Figure 2 below outlines parsing of xml file with XmlTextReader

 Imports System.IO
Imports System.Xml
Module ParsingUsingXmlTextReader
Sub Main()
Dim m_xmlr As XmlTextReader
'Create the XML Reader
m_xmlr = New XmlTextReader("C:\Personal\family.xml")
'Disable whitespace so that you don't have to read over whitespaces
m_xmlr.WhiteSpaceHandling = WhiteSpaceHandling.NONE
'read the xml declaration and advance to family tag
m_xmlr.Read()
'read the family tag
m_xmlr.Read()
'Load the Loop
While Not m_xmlr.EOF
'Go to the name tag
m_xmlr.Read()
'if not start element exit while loop
If Not m_xmlr.IsStartElement() Then
Exit While
End If
'Get the Gender Attribute Value
Dim genderAttribute = m_xmlr.GetAttribute("gender")
'Read elements firstname and lastname
m_xmlr.Read()
'Get the firstName Element Value
Dim firstNameValue = m_xmlr.ReadElementString("firstname")
'Get the lastName Element Value
Dim lastNameValue = m_xmlr.ReadElementString("lastname")
'Write Result to the Console
Console.WriteLine("Gender: " & genderAttribute _
& " FirstName: " & firstNameValue & " LastName: " _
& lastNameValue)
Console.Write(vbCrLf)
End While
'close the reader
m_xmlr.Close()
End Sub
End Module

Parsing XML with XmlDocument

The XmlDocument class is modeled based on Document Object Model. XmlDocument class is appropriate if you need to extract data in a non-sequential manner. Figure 3 below outlines parsing of xml file with XmlDocument

 Imports System.IO
Imports System.Xml
Module ParsingUsingXmlDocument
Sub Main()
Try
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
'Create the XML Document
m_xmld = New XmlDocument()
'Load the Xml file
m_xmld.Load("C:\CMS\Personal\family.xml")
'Get the list of name nodes
m_nodelist = m_xmld.SelectNodes("/family/name")
'Loop through the nodes
For Each m_node In m_nodelist
'Get the Gender Attribute Value
Dim genderAttribute = m_node.Attributes.GetNamedItem("gender").Value
'Get the firstName Element Value
Dim firstNameValue = m_node.ChildNodes.Item().InnerText
'Get the lastName Element Value
Dim lastNameValue = m_node.ChildNodes.Item().InnerText
'Write Result to the Console
Console.Write("Gender: " & genderAttribute _
& " FirstName: " & firstNameValue & " LastName: " _
& lastNameValue)
Console.Write(vbCrLf)
Next
Catch errorVariable As Exception
'Error trapping
Console.Write(errorVariable.ToString())
End Try
End Sub
End Module

You will see the following result for both

Gender: Male FirstName: Tom LastName: Smith

Gender: Female FirstName: Dale LastName: Smith

http://www.codeproject.com/Articles/4826/XML-File-Parsing-in-VB-NET

[vb.net]XML File Parsing in VB.NET的更多相关文章

  1. ILJMALL project过程中遇到Fragment嵌套问题:IllegalArgumentException: Binary XML file line #23: Duplicate id

    出现场景:当点击"分类"再返回"首页"时,发生error退出   BUG描述:Caused by: java.lang.IllegalArgumentExcep ...

  2. Binary XML file line #2: Error inflating

    06-27 14:29:27.600: E/AndroidRuntime(6936): FATAL EXCEPTION: main 06-27 14:29:27.600: E/AndroidRunti ...

  3. Android项目部署时,发生AndroidRuntime:android.view.InflateException: Binary XML file line #168: Error inflating class错误

    这个错误也是让我纠结了一天,当时写的项目在安卓虚拟机上运行都很正常,于是当我部署到安卓手机上时,点击登陆按钮跳转到用户主界面的时候直接结束运行返回登陆界面.    当时,我仔细检查了一下自己的代码,并 ...

  4. ADT开发AndroidManifest.xml file missing错误

    一个错误“AndroidManifest.xml file missing”但helloworld目录下有此文件,几番google仍没能解决.想起曾经在网络上看到的一个修复project的办法,抱着死 ...

  5. SVN :This XML file does not appear to have any style information associated with it.

    SVN :This XML file does not appear to have any style information associated with it. The document tr ...

  6. The AndroidManifest.xml File

    manifest (船运的)载货清单 http://www.android-doc.com/guide/topics/manifest/manifest-intro.html Every applic ...

  7. bug_ _图片_android.view.InflateException: Binary XML file line #1: Error inflating class <unknown>

    =========== 1   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zgan.communit ...

  8. bug_ _ android.view.InflateException: Binary XML file line #2: Error inflating class <unknown

    ========= 5.0     android异常“android.view.InflateException: Binary XML file line # : Error inflating ...

  9. How to: Read Object Data from an XML File

    This example reads object data that was previously written to an XML file using the XmlSerializer cl ...

随机推荐

  1. 1 、Linux-Rhel6终端介绍-Shell提示符

    1.Linux 终端介绍 tty-控制台终端: RHEL6 tty1-tty6  tty就是图形界面 从图形界面切换到字符界面: ctrl+shift+alt +F2~F6 从字符界面切换图形或字符: ...

  2. java 线程的堵塞

    //线程的阻塞 // //线程 class xc1 implements Runnable{ public void run(){ for(int i=1;i<=30;i++){ System. ...

  3. 使用 Jmeter 做 Web 接口测试

    接口测试概述 定义 API testing is a type of software testing that involves testing application programming in ...

  4. 创建sa账号

    ①以windows身份验证的方式默认登陆 ②选择安全性下的登录名中的sa账号,右键选择属性,进行相关项的设置 ③将sa账号的状态中对应的登录项由之前的禁用,改为已启用 ④将sa对应的密码进行修改为自己 ...

  5. 自动化测试selenium+java 第三章

    import java.sql.Time;import java.util.concurrent.TimeUnit; import org.junit.BeforeClass;import org.o ...

  6. 去除DEDECMS后台预览文章URL地址多余的数字信息

    在使用织梦模板时发现这样一个问题:在后台预览文章的时候,出现的文章网址尽管是静态URL,但是会在网址的尾部出现问号并跟随一个时间戳,在复制URL时就显得很不方便.那么如何解决这一问题呢? 经过查找资料 ...

  7. Java介绍(重要特点)

    Java语言平台版本 JavaSE标准版本,是JavaME 和Java EE的基础,能够开放基本桌面程序. JavaME 一句话,安卓开发. JavaEE 一句话,网页开发. Java重要特性(跨平台 ...

  8. web form 控件

    webform的简单控件1.Label:文本显示,编译后是span属性:颜色,样式,边线宽度2.Literal:纯文本显示,编译后是text 3.TextBox:文本框TextMode-密码框.文本域 ...

  9. ComponentCount 与 ControlCount 区别

       ShowMessage(panel.ComponentCount.ToString);  ShowMessage(panel.ControlCount.ToString);componetcou ...

  10. {CSDN}{英雄会}{反相互}

    思路: 给定一个字符串,求两个不重叠的字串,他们翻转互补.其中一个字符串可以是删掉最多两个字符的原字符串子串. 动态规划,由于可以对子串进行删除操作,我首先想到了LCS问题,但需要枚举所有的长度,这样 ...