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. Linux Bash 使用$?来防止一些误删操作

    在shell脚本中如果不加任何检查机制,很有可能导致误删的出现,例如: cd $remove_directory rm * 这段代码的目的是删除目标目录下所有的文件.但是如果目标目录由于输入错误等原因 ...

  2. Javascript 基础知识学习--javascript中的参数传递都是按值传递的

    ECMAScript中所有函数的参数传递都是按值传递的,无论参数是值类型还是引用类型的.过去我跟大多数人一样觉得跟传值类型相关. 自己写了一个测试的例子,确实如此 function add(a) { ...

  3. 65. Reverse Integer && Palindrome Number

    Reverse Integer Reverse digits of an integer. Example1: x =  123, return  321 Example2: x = -123, re ...

  4. Install FFMPEG and FFMPEG-PHP in CentOS 6 with Virtualmin

    Install FFMPEG and FFMPEG-PHP in CentOS 6 with Virtualmin  1 year ago -  by Daniel -  howto centos v ...

  5. host DNS 访问规则

    昨天站点一直出现302循环重定向问题,捣鼓了半天才解决,原来是hosts和dns配置问题. 注:当你的站点出现循环重定向时,首先应该关注的hosts以及dns配置,确保无误. 下面记录下相关知识点: ...

  6. Zepto源码

    // Zepto.js // (c) 2010-2016 Thomas Fuchs // Zepto.js may be freely distributed under the MIT licens ...

  7. mac java目录

    /Library/Java/JavaVirtualMachines/jdk1.7.0_10.jdk/Contents/Home mac java的安装目录为 /Library/Java/JavaVir ...

  8. ie6并不是不支持!important

    之前对ie6接触不多,并且认识也不深,虽然知道ie6中的!important很特别,但是并没有记住特别在哪里~今天就记录一下吧! 首先,很多人说ie6是不支持!important的,其实这个一个错误的 ...

  9. 百度地图API示例之添加定位相关控件

    代码 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" cont ...

  10. js事件委托,可以使新添加的元素具有事件(event运用)

    miaov视频教程  http://study.163.com/course/courseMain.htm?courseId=231002 <!DOCTYPE html PUBLIC " ...