Sie sind auf Seite 1von 4

9/21/2015

XMLFileParsinginVB.NETCodeProject

XMLFile Parsing in VB.NET


Pratik Desai,21 Aug 2003

Rate:

4.6272votes

Exploring various methods to parse anXMLfile in a .NET environment

Is your email address OK?You are signed up for our newsletters but your email address is
either unconfirmed, or has not been reconfirmed in a long time. Please clickhereto have a
confirmation email sent so we can confirm your email address and start sending you
newsletters again. Alternatively, you canupdateyour subscriptions.

Introduction
ParsingXMLfiles has always been time consuming and sometimes tricky. .NET framework provides powerful
new ways of parsingXML. The various techniques know to parsexmlfiles with .NET framework are
usingXmlTextReader,XmlDocument,XmlSerializer,DataSetandXpathDocument. I will explore
theXmlTextReaderandXmlDocumentapproach here.

TheXmlFile
Figure 1 outlines thexmlfile that will be parsed.
HideCopy Code

<?xmlversion="1.0"encoding="UTF8"?>
<family>
<namegender="Male">
<firstname>Tom</firstname>
<lastname>Smith</lastname>
</name>
<namegender="Female">
<firstname>Dale</firstname>
<lastname>Smith</lastname>
</name>
</family>
Figure1:Xmlfile

ParsingXMLwithXMLTextReader
UsingXmlTextReaderis appropriate when the structure of theXMLfile is relatively simple. Parsing
withXmlTextReadergives you a pre .net feel as you sequentially walk through the file usingRead()and
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%200px%3B%20border%3A%2

1/4

9/21/2015

XMLFileParsinginVB.NETCodeProject

get data usingGetAttribute()andReadElementString()methods. Thus while


usingXmlTextReaderit is up to the developer to keep track where he is in theXmlfile
andRead()correctly. Figure 2 below outlines parsing ofxmlfile withXmlTextReader
HideShrink

Copy Code

ImportsSystem.IO
ImportsSystem.Xml
ModuleParsingUsingXmlTextReader
SubMain()
Dimm_xmlrAsXmlTextReader
'CreatetheXMLReader
m_xmlr=NewXmlTextReader("C:\Personal\family.xml")
'Disablewhitespacesothatyoudon'thavetoreadoverwhitespaces
m_xmlr.WhiteSpaceHandling=WhiteSpaceHandling.NONE
'readthexmldeclarationandadvancetofamilytag
m_xmlr.Read()
'readthefamilytag
m_xmlr.Read()
'LoadtheLoop
WhileNotm_xmlr.EOF
'Gotothenametag
m_xmlr.Read()
'ifnotstartelementexitwhileloop
IfNotm_xmlr.IsStartElement()Then
ExitWhile
EndIf
'GettheGenderAttributeValue
DimgenderAttribute=m_xmlr.GetAttribute("gender")
'Readelementsfirstnameandlastname
m_xmlr.Read()
'GetthefirstNameElementValue
DimfirstNameValue=m_xmlr.ReadElementString("firstname")
'GetthelastNameElementValue
DimlastNameValue=m_xmlr.ReadElementString("lastname")
'WriteResulttotheConsole
Console.WriteLine("Gender:"&genderAttribute_
&"FirstName:"&firstNameValue&"LastName:"_
&lastNameValue)
Console.Write(vbCrLf)
EndWhile
'closethereader
m_xmlr.Close()
EndSub
EndModule
Figure 2:XmlParsing withXmlTextReader

ParsingXMLwithXmlDocument
TheXmlDocumentclass is modeled based on Document Object Model.XmlDocumentclass is appropriate if
you need to extract data in a nonsequential manner. Figure 3 below outlines parsing ofxmlfile
withXmlDocument
HideShrink

Copy Code

ImportsSystem.IO
ImportsSystem.Xml
ModuleParsingUsingXmlDocument
SubMain()
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%200px%3B%20border%3A%2

2/4

9/21/2015

XMLFileParsinginVB.NETCodeProject

Try
Dimm_xmldAsXmlDocument
Dimm_nodelistAsXmlNodeList
Dimm_nodeAsXmlNode
'CreatetheXMLDocument
m_xmld=NewXmlDocument()
'LoadtheXmlfile
m_xmld.Load("C:\CMS\Personal\family.xml")
'Getthelistofnamenodes
m_nodelist=m_xmld.SelectNodes("/family/name")
'Loopthroughthenodes
ForEachm_nodeInm_nodelist
'GettheGenderAttributeValue
DimgenderAttribute=m_node.Attributes.GetNamedItem("gender").Value
'GetthefirstNameElementValue
DimfirstNameValue=m_node.ChildNodes.Item(0).InnerText
'GetthelastNameElementValue
DimlastNameValue=m_node.ChildNodes.Item(1).InnerText
'WriteResulttotheConsole
Console.Write("Gender:"&genderAttribute_
&"FirstName:"&firstNameValue&"LastName:"_
&lastNameValue)
Console.Write(vbCrLf)
Next
CatcherrorVariableAsException
'Errortrapping
Console.Write(errorVariable.ToString())
EndTry
EndSub
EndModule
Figure 3:XmlParsing withXmlDocument

Compilation and Result


Make sure you havevbc.exein your path. From the command prompt go
toC:\Personal>.CompileParsingUsingXmlTextReader.vbandParsingUsingXmlDocument.vb.
HideCopy Code

C:\Personal>vbc/out:ParsingUsingXmlTextReadervb.exeParsingUsingXmlTextReader.vb
C:\Personal>vbc/out:ParsingUsingXmlDocumentvb.exeParsingUsingXmlDocument.vb

When you run the individual program


HideCopy Code

C:\Personal>ParsingUsingXmlTextReadervb.exe

OR
HideCopy Code

C:\Personal>ParsingUsingXmlDocumentvb.exe

You will see the following result for both


HideCopy Code

Gender:MaleFirstName:TomLastName:Smith
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%200px%3B%20border%3A%2

3/4

9/21/2015

XMLFileParsinginVB.NETCodeProject

Gender:FemaleFirstName:DaleLastName:Smith

Conclusion
There are different ways to parseXMLfiles and the best method depends on your situation and the
programming style preferred.

License
This article has no explicit license attached to it but may contain usage terms in the article text or the
download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be foundhe

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22header%22%20style%3D%22margin%3A%200px%3B%20padding%3A%200px%3B%20border%3A%2

4/4

Das könnte Ihnen auch gefallen