Process XML Using DOM Model in Powershell

The XML Document Object Model (DOM) treats XML data as a standard set of objects and is used to process XML data in memory. The System.Xml namespace provides a programmatic representation of XML documents, fragments, nodes, or node-sets. It is based on the World Wide Web Consortium (W3C) DOM Level 1 Core and the DOM Level 2 Core recommendations.

The XmlDocument class represents an XML document. It includes members for retrieving and creating all other XML objects. Using the XmlDocument, and its related classes, you can construct XML documents, load and access data, modify data, and save changes.

The XML Document Object Model (DOM) class is an in-memory representation of an XML document. The DOM allows you to programmatically read, manipulate, and modify an XML document. The XmlReader class also reads XML; however, it provides non-cached, forward-only, read-only access.

I wrote another script in the powershell, but used XmlDocument this time.

A sample XML input file : products.xml

I just generated from MS SQL 2008 using select * from Products for xml raw TYPE,ROOT(‘Products”)

<?xml version="1.0"?>
<Products>
  <row ProdId="1" ProdName="BOND" />
  <row ProdId="2" ProdName="EQUITY" />
  <row ProdId="3" ProdName="FX" />
  <row ProdId="4" ProdName="MUTUAL FUND" />
  <row ProdId="5" ProdName="ETF" />
  <row ProdId="6" ProdName="OPTION" />
  <row ProdId="7" ProdName="INSURANCE" />
  <row ProdId="8" ProdName="DEPOSIT" />
</Products>

A parsing script in XmlDocument: xmlparser1.ps1

# xmlparser1.ps1
[System.Xml.XmlDocument] $xdoc = new-object System.Xml.XmlDocument
$xfile = resolve-path("products.xml")
$xdoc.load($xfile)
write-host "`nreading from products.xml`n"
$rows = $xdoc.selectnodes("/Products/row") # XPath is case sensitive
$rowcount=0
foreach ($row in $rows) {
  $ProdId = $row.getAttribute("ProdId")
  $ProdName = $row.getAttribute("ProdName")
  write-host "Product ID = $ProdId Name = $ProdName"
  $rowcount++
}
write-host "`Total Rows: $rowcount"

Execution Results

PS C:\henry416\> .\xmlparser1.ps1
reading from products.xml
Product ID = 1 Name = BOND
Product ID = 2 Name = EQUITY
Product ID = 3 Name = FX
Product ID = 4 Name = MUTUAL FUND
Product ID = 5 Name = ETF
Product ID = 6 Name = OPTION
Product ID = 7 Name = INSURANCE
Product ID = 8 Name = DEPOSIT
Total Rows: 8

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