Skip to content

Instantly share code, notes, and snippets.

@jeffpatton1971
Last active May 28, 2017 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffpatton1971/730c38b91471fe51d0dd to your computer and use it in GitHub Desktop.
Save jeffpatton1971/730c38b91471fe51d0dd to your computer and use it in GitHub Desktop.
A collection of PowerShell functions for creating xml data files.
Function New-XmlDocument
{
[CmdletBinding()]
Param
(
[string]$Root,
[string[]]$Elements
)
Begin
{
[System.Xml.XmlDocument]$xDoc = New-Object System.Xml.XmlDocument
[System.Xml.XmlElement]$xRoot = $xDoc.CreateElement($Root)
$Result = $xDoc.AppendChild($xRoot)
Write-Verbose $Result.OuterXml
$xDocElement = $xDoc.DocumentElement
}
Process
{
foreach ($Element in $Elements)
{
[System.Xml.XmlElement]$xElement = $xDoc.CreateElement($Element)
$Result = $xDocElement.AppendChild($xElement)
Write-Verbose $Result.OuterXml
}
}
End
{
return $xDoc
}
}
Function Add-XmlElement
{
[CmdletBinding()]
Param
(
[System.Xml.XmlDocument]$xDoc,
[string]$Node,
[System.Xml.XmlElement[]]$Element
)
Begin
{
$xNode = $xDoc.GetElementsByTagName($Node)
foreach ($xn in $xNode)
{
#
# More than one element returned, add to the empty one
#
if ($xn.IsEmpty)
{
$xNode = $xn
}
}
Write-Verbose $Node
}
Process
{
foreach ($E in $Element)
{
$Result = $xNode.AppendChild($E)
foreach ($r in $Result)
{
Write-Verbose $r.outerxml
}
}
}
End
{
return $xDoc
}
}
Function New-XmlElement
{
[CmdletBinding()]
Param
(
[System.Xml.XmlDocument]$xDoc,
[string]$Name,
[string[]]$ChildNodes,
[string]$Property,
[string]$Value
)
Begin
{
}
Process
{
[System.Xml.XmlElement]$xElement = $xDoc.CreateElement($Name)
foreach ($ChildNode in $ChildNodes)
{
$Result = $xElement.AppendChild($xDoc.CreateElement($ChildNode))
Write-Verbose $Result.OuterXml
}
if ($Property -and $Value)
{
[System.Xml.XmlAttribute]$xAttribute = $xDoc.CreateAttribute($Property)
$xAttribute.Value = $Value
$Result = $xElement.SetAttributeNode($xAttribute)
Write-Verbose $Result.OuterXml
}
}
End
{
return $xElement
}
}
Function Set-XmlAttribute
{
[CmdletBinding()]
Param
(
[System.Xml.XmlDocument]$xDoc,
[string]$Node,
[string]$Attribute,
[string]$Value
)
Begin
{
}
Process
{
($xDoc.GetElementsByTagName($Node)).SetAttribute($Attribute,$Value)
}
End
{
}
}
@jeffpatton1971
Copy link
Author

Fixed an issue in add-xmlelement where getelementsbytagname returns more than one element. At the moment this works, I think the better solution may be to create an insert-xmlement, I should also perhaps change the code to getelemenetbyid, but that requires a valid DTD in the xml.

@weiyentan
Copy link

If i can make a comment There is no comment based help so it becomes difficult to use for those ppl that are unfamiliar with this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment