August 25, 2015

PowerShell - Working with XML

PowerShell supports many of the .Net data types, one of the intesresting type is XML document. Lets see how we can use this type to process XML.

We have a string variable with items list xml:
$items = "<items>" +
    "<item code='I001' name='Laptop'/>" +
    "<item code='I002' name='Tablet'/>" +
    "<item code='I003' name='CellPhone'/>" +
    "</items>"

Now define a new variable with xml data type and assign this string to that variable
[xml]$itemsXml = $items

We can check the Xml back in string format.
$itemsXml.items.InnerXml

This will show the items in table format
$itemsXml.items.ChildNodes

It will also allow you even to modify the xml content.
$itemsXml.items.ChildNodes[0].Attributes["name"].InnerText = "Notebook"

Again display the child nodes to see the effect.
$itemsXml.items.ChildNodes

Lets create a new item:

$xmlElement =  $itemsXml.CreateElement("item")
$xmlNodeNew =  $itemsXml.CreateTextNode("item")
$xmlNodeTemp = $xmlElement.AppendChild($xmlNodeNew)

$xmlAttCode = $itemsXml.CreateAttribute("code")
$xmlAttCode.Value = "I004"
$xmlNodeTemp = $xmlElement.Attributes.Append($xmlAttCode)

$xmlAttName = $itemsXml.CreateAttribute("name")
$xmlAttName.Value = "New Item"
$xmlNodeTemp = $xmlElement.Attributes.Append($xmlAttName)

$itemsXml.LastChild.AppendChild($xmlElement);

Query child nodes to see the effect.
$itemsXml.items.ChildNodes

No comments:

Post a Comment