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 you have to be left in the dark on OS patches
- Is Microsoft mismanaging Windows on ARM?
- Dealing with spam surrogates
- Why 3G broadband can be better and cheaper than ADSL
- Is Twitter bad for business?
- Publishing your email address isn't a security disaster
- Why you'll need a fax machine to develop iOS apps
- Learning to adapt to the mobile web
- Why you shouldn't use WPS on your Wi-Fi network
- Disabled users suffer when software breaks the rules
- Laptop bag reviews: nine tested
- Sony VAIO T Series Ultrabook review: first look
- Revealed: the military standards and robots HP uses to test its laptops
- Windows 8: multi-monitors and double standards?
- Why is TalkTalk's year-old porn filter suddenly big news?
- Why are laptop screens so far behind mobiles?
- HP EliteBook Folio review: first look
- The shoebox-sized all-in-one printer
- Forget the Ultrabook: here comes the HP Sleekbook
- HP Spectre XT review: first look
- Autonomy's Lynch joins 27,000 on way out of HP
- ICO: no fines for breaking cookie rules
- HP set to slash up to 30,000 jobs
- Government sites to miss cookie deadline
- Microsoft tweaks multi-monitor support in Windows 8
- Apple patches Leopard, despite ending support last year
- Defra opens rural broadband funding applications
- BT's broadband sales surpass calls revenue
- Apple patches multiple security issues
- FBI warns travellers to beware attacks via hotel Wi-Fi
advertisement
