Reading XML with the XmlReader in Powershell

The XmlReader class in .Net Framework reads XML data from a stream or file. It provides non-cached, forward-only, read-only access to XML data. I wrote a simple program in powershell to explore XmlReader class as belows. Have fun!

A sample XML input file: books.xml

<?xml version="1.0"?>
<books>
 <book> 
   <author>Carson</author>
   <price>31.95</price>
   <pubdate>05/01/2001</pubdate>
 </book>
 <pubinfo>
   <publisher>MSPress</publisher>
   <state>WA</state>
 </pubinfo>
</books>

A powershell script: xmlreader1.ps1

##  
# xmlreader1.ps1  
## 
$PWD=Get-Location
$xmlfile=$PWD.Path+"\books.xml"

# Create XML Reader  
$reader = [system.Xml.XmlReader]::Create($xmlfile) 

# Parse the XML document.  
$result=$reader.Read()  
$reader.ReadStartElement("books")

# start book node
"The following is from book:"
$reader.ReadStartElement("book")

# Read and Display auther  
$reader.ReadStartElement("author")     
"author: {0}" -f $reader.ReadString()  
$reader.ReadEndElement()  

# Read and display price  
$reader.ReadStartElement("price")  
"price: {0}" -f $reader.ReadString()  
$reader.ReadEndElement() 
# Read and display pubdate
$reader.ReadStartElement("pubdate")  
"pubdate: {0}" -f $reader.ReadString()  
$reader.ReadEndElement()

# end book node
""
$reader.ReadEndElement()

# start pubinfo node
"The following is from pubinfo:"
$reader.ReadStartElement("pubinfo")

# Read and Display publisher  
$reader.ReadStartElement("publisher")     
"publisher: {0}" -f $reader.ReadString()  
$reader.ReadEndElement()  

# Read and display state  
$reader.ReadStartElement("state")  
"state: {0}" -f 
$reader.ReadString()  

$reader.ReadEndElement() 
# end pubinfo node

$reader.ReadEndElement()
# End of Script 

Execution Result

PS C:\henry416\> .\xmlreader1.ps1

The following is from book:
author: Carson
price: 31.95
pubdate: 05/01/2001

The following is from pubinfo:
publisher: MSPress
state: WA

About henry416
I am a computer technology explorer and an university student based on Toronto. If you have any question, please feel free to discuss and comment here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s