widsnet.com
22Nov/120

Create XML with Powershell

Some powershell XML code and functions that can be useful sometime...

# Document creation
[x m l]$newXML = New-Object system.Xml.XmlDocument 
$newXML.LoadXml('<?xml version="1.0" encoding="utf-16"?><root></root>')

# Creation of a the first element
$xmlElt = CreateElement -xml $newXML -name "task"

# Add the element to the document
$newXML.LastChild.AppendChild($xmlElt) | Out-Null

# Creation of a second element
$xmlElt = CreateElement -xml $newXML -name "task"

# Create an attribute
SetAttribute -xml $newXML -element $xmlElt -name "xmlns" -text "http://random.url"

# Create another attribute
SetAttribute -xml $newXML -element $xmlElt -name "Another" -text "Attribute"

# Create a child element
$xmlSubElt = CreateElement -xml $newXML -parent $xmlElt -name "ChildElement" -text "Value"

# Create another child element
$xmlSubElt = CreateElement -xml $newXML -parent $xmlElt -name "AnotherChild"

# Create an attribute to the child
SetAttribute -xml $newXML -element $xmlSubElt -name "Attribute" -text "inChild"

# Add the second element to the document
$newXML.LastChild.AppendChild($xmlElt) | Out-Null

# Save to a file
$newXML.Save("c:\Temp\out.xml")

function SetAttribute {
    param($xml, $name, $text, $element)
    $xmlAtt = $xml.CreateAttribute($name)
    $xmlAtt.Value = $text
    $element.Attributes.Append($xmlAtt) | Out-Null
}

function CreateElement {
    param($xml, $name, $text, $parent)
    $xmlElt = $xml.CreateElement($name)
    if ($text) {
        $xmlText = $xml.CreateTextNode($text)
        $xmlElt.AppendChild($xmlText) | Out-Null
    }
    If ($parent) {
        $parent.AppendChild($xmlElt) | Out-Null
    }
    $xmlElt
}

And the output looks like this

<?xml version="1.0" encoding="utf-16"?>
<root>
<task />
<task xmlns="http://random.url" Another="Attribute">
<ChildElement>Value</ChildElement>
<AnotherChild Attribute="inChild" />
</task>
</root>
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.