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'/>" +

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.

This will show the items in table format

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.

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)


Query child nodes to see the effect.

No comments:

Post a Comment