May 012015
 

Here are some sample PowerShell commands to manipulate XML contents in memory and then later dump them to an XML file. I’ve added comments inline to explain a line of PowerShell command.

#Clear output
cls

#Sample XML content
$xml = @'
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book genre="novel" style="hardcover">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>19.95</price>
</book>
<book genre="novel" style="other">
<title>The Poisonwood Bible</title>
<author>
<first-name>Barbara</first-name>
<last-name>Kingsolver</last-name>
</author>
<price>11.99</price>
</book>
<book genre="novel" style="paperback">
<title>The Bean Trees</title>
<author>
<first-name>Barbara</first-name>
<last-name>Kingsolver</last-name>
</author>
<price>5.99</price>
</book>
</bookstore>
'@

# Dump XML to output window
$xml.InnerXml

#Get all attributes named "genre" from above XML
$nodes = $xml.SelectNodes("//@genre")
$nodes.Count 
#Output: 3

#Get first book in the XML
$firstbook = $xml.SelectSingleNode("/bookstore/book[1]")
$firstbook.InnerXml 
#Output: <title>The Handmaid's Tale</title><author><first-name>Margaret</first-name><last-name>Atwood</last-name></author><price>19.95</price>

# Using Select-Xml: Get last book in the XML
$selxml = Select-Xml -Xml $xml -XPath "/bookstore/book[last()]"
$selxml.ToString() 
#Output: <title>The Bean Trees</title><author><first-name>Barbara</first-name><last-name>Kingsolver</last-name></author><price>5.99</price>

# Filter out nodes based on conditions, dump titles of books whose price is greater than 11
$xml.SelectNodes("/bookstore/book[price>11]/title") | Format-Table
#Output: #text 
 # ----- 
 #The Handmaid's Tale 
 #The Poisonwood Bible
 
# Modify XML value of a node, change price
$xml.SelectSingleNode("/bookstore/book[price<11]/price") #Old price
$xml.SelectSingleNode("/bookstore/book[price<11]/price").InnerText = 10 #New Price
$xml.SelectSingleNode("/bookstore/book[price<11]/price") #Print new price
#Output: #text 
 #----- 
 #5.99 
 #10

#Save XML
$xml.Save("$env:userprofile\\desktop\\testxml.xml")

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.