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
advertisement
- Getting to grips with Microsoft's IT Health Environment Scanner
- Virtualise your servers
- The changing face of travel gadgets
- Build your own distributed file system
- The bulletproof Dell that costs an arm and a leg
- Microsoft Office 2010 Technical Preview: Q&A
- Lawnmowers, the TyTN II and one odd insurance request
- There'll never be a bulletproof OS
- How far can we trust apps?
- Five nice touches in Outlook 2010
- Need a bit of extra Christmas cash? Grass up your boss, says BSA
- Photoshop Mobile on Android review: first look
- ATI Radeon HD 5970: 42% more expensive in the UK
- Office 2010 Beta – 32-bit or 64-bit – The Choice is Clear
- Why Britain's watchdogs have fewer teeth than goldfish
- Tabbed documents: how to make Office 2010 great
- Outlook 2010 People Pane – does it spell death to Xobni
- Microsoft Outlook 2010 screenshots
- Co-Authoring in Word 2010 and SharePoint Foundation 2010
- Microsoft Outlook 2010 screenshots: Backstage view
- Gmail adds offline attachments
- Mobile data surges up by 16% in October
- OFT: Google isn't harming consumers
- £90 million buys South Yorkshire 25Mbits/sec broadband
- Twitter ready to splash out... and run ads
- LogMeIn Express offers fuss-free screen sharing
- Kindle calms customers with library update
- Photoshop app arrives on Android
- Google: we won't remove "disturbing" Obama image
- Internet Explorer hit by zero-day misery
advertisement
Printed from www.pcpro.co.uk

