More XML with PowerShell
Posted on 8 Mar 2007 at 11:36
With help from shiny power, Thomas Lee gets serious with PowerShell, updating the XML order document and using the xml reader class.
In last month's column, I looked at some of the simpler aspects of XML, illustrated with some basic PowerShell scripts. In this month's column, I'll be venturing a bit deeper into how to use PowerShell with XML.
You may recall from last month that you can create an XML DOM document by typing a PowerShell command line something like this:
$orderdoc = [xml] (Cat D:\Xml\Order.xml)
This assumes that a file called order.xml already exists in the folder D:\Xml and that the XML contained in the file is valid. We've produced a valid file, which you'll find at www.pcpro.co.uk/links/151dotnet.
In the screenshot below, you can see this XML document as viewed using the freeware utility XMLPad. Developed by WMHelp (www.wmhelp.com), XMLPad is a most useful tool when working with XML, especially since it's free. As you can see, the XML file contains a root node <Order>, which has two subnodes - <OrderHeader> and <OrderLines> - both of which have their own subnodes. As I noted last month, you can directly address specific nodes by using PowerShell, so to obtain the customer name you could just enter $OrderDoc.Order.Orderheader.Customername, while to get the customer number you'd specify $OrderDoc.Order.Orderheader.CustomerID. XML tags are case sensitive, so having an opening tag <order> and a closing tag </Order> would generate an error, since <order> is left open. Although XML is case sensitive, PowerShell isn't, which means in the earlier example to retrieve a customer ID, you could have specified either $orderdoc.order.orderheader.customerID or $ORDERDOC.ORDER.ORDERHEADER.CUSTOMERID (or any other combination of capitalisation). To be on the safe side, therefore, I generally recommend using the same node names as specified in the XML (case sensitively) to avoid any confusion in your PowerShell code.
Updating an XML document
Updating the XML Order Document using PowerShell is straightforward using the .NET XML Document and XML Element object types. The following code reads the existing order, adds a new line to the order and then writes the updated order back to a new file:
#Addline.ps1 - adds an order line to order in d:\foo\order.xml
# writes order to d:\foo
eworder.xml
# Step 1 - create document in memory
$doc=[xml] (cat d:\foo\order.xml)
# Step 2 - create order line element
$ol=$doc.CreateElement("OrderLine")
# Step 3 - create and populate sub items
$Item = $doc.CreateElement("ItemID")
$item.Set_InnerText("876543")
$Itemd = $doc.CreateElement("ItemDescription")
$itemd.Set_InnerText("Invisible Widgets")
$Numordered = $doc.CreateElement("NumberOrdered")
$numOrdered.Set_InnerText("21")
$Price = $doc.CreateElement("Price")
$price.Set_Innertext("321.12")
# Step 4 - Now build up orderline
$ol.AppendChild($item)
$ol.AppendChild($itemd)
$ol.AppendChild($numordered)
$ol.AppendChild($price)
# Step 5 finally, add the order line to the order.
$doc.order.orderlines.appendchild($ol)
#Step 6 - save the document away.
$doc.save("d:\foo\Neworder.xml")
There are six steps to adding the order line. First, the document is opened and assigned to $doc. Note that this succeeds only if the XML document is well formed, but for simplicity I've omitted any error-handling code to recover from errors in the XML. Step 2 creates a new empty XML element called $ol, which represents a new order line. The element is created using the CreateElement method of an XML Document. In Step 3, the CreateElement method is used to create the order line's component elements ($item, $itemd, $numordered, and $price). The Set_InnerText method is used to assign a value to each of these component elements. In Step 4, these individual components are appended to the $ol value, which creates a complete new order line. With Step 5, this new order line element is appended to the order document's orderline element and finally, in Step 6, the updated order is written back to a new file called (d:\foo
From around the web
advertisement
- Why virtualisation hasn't slowed the growth of data
- How to make Google AdWords work for your business
- The curse of sloppily written software
- Paying for your crimes with Bitcoin
- Behind the scenes: tech support for Formula 1
- The security risk of fat fingers
- Why Windows Phone 7 isn't quite ready for business
- When will Microsoft stop fiddling with Windows 8?
- Flash down the pan?
- Metro Style apps vs desktop applications
- Chrome's shine getting lost in translation
- BytePac: the cardboard hard disk enclosure
- How tech loosens our grip on reality
- Hokum watch: Safer Internet Day
- Why I'm deleting Adobe from my PC
- Prepare to be patronised: it's Safer Internet Day
- Dear Sony, Samsung and every other tech company in the world: stop trying to be Apple
- Will Apple's Final Cut Pro X update placate the pros?
- Smartr Contacts for iPhone review
- Switching to Office 365's Outlook Web App
- VeriSign slammed for security breach cover-up
- SAP willing to share HANA with Oracle
- Why using a tablet could harm your health
- New RIM boss: no need for drastic change
- RIM founders fall on their swords
- Slow economy helps boost Red Hat revenue by 23%
- Google+ pages get multiple admins
- One in five companies lack card industry compliance
- Oil industry warns hacking attacks could kill
- British workers fear email monitoring
advertisement
