Reading XML with the XmlReader in Powershell
October 5, 2012 Leave a comment
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