Xml Module 6.5 by Joel Bennett 7 months ago (modification of post by Joel Bennett view diff)
View followups from Jaykul | diff | embed code: <script type="text/javascript" src="/img/spacer.gif"> download | new post
A complete set of XML functionality (especially if you don’t have PSCX), including reading and writing xml files (import-xml, export-xml), selecting (via xpath), updating, transforming and creating new xml documents.
In particular:
A DSL for creating XML documents.
Convert-Xml which supports parameters so you can use XSLT which require parameters
Select-XML which leverages Remove-XmlNamespace to simplify simple xml queries by allowing you to leave out the namespaces. It is important to note that this means that the returned results will not have namespaces in them, even if the input XML did.
ALSO NOTE: only raw XmlNodes are returned from Select-Xml, so the output isn’t compatible with the built in Select-Xml — instead, it’s equivalent to using it the way I usually do: Select-Xml ... | Select-Object -Expand Node
Update-Xml which allows you to append, insert, remove, and replace values in XML Documents
Remove-XmlElement which can remove nodes or attributes by namespace to clean-up designer-generated XML
In this Version: I added Remove-XmlElement, added a Parameters parameter to New-XmlDocument, and fixed a bug in New-XElement which prevented using attribute values with dashes in them.
- #requires -version 2.0
- # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492
- # to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
- # and prefixes are removed from all XML nodes (by an XSL transform) before searching.
- # IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
- # Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
- # with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
- # Version History:
- # Select-Xml 2.0 This was the first script version I wrote.
- # it didn't function identically to the built-in Select-Xml with regards to parameter parsing
- # Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
- # BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
- # Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
- # Version 3.0 Added New-XDocument and associated generation functions for my XML DSL
- # Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
- # Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
- # Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
- # Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags.
- # Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml)
- # Version 4.3 Added a Path parameter set to Format-Xml so you can specify xml files for prety printing
- # Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument)
- # Work around possible variable slipping on null values by:
- # 1) allowing -param:$value syntax (which doesn't fail when $value is null)
- # 2) testing for -name syntax on the value and using it as an attribute instead
- # Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms!
- # Note: when using strings for xslt, make sure you single quote them or escape the $ signs.
- # Version 4.7 Fixed a typo in the namespace parameter of Select-Xml
- # Version 4.8 Fixed up some uses of Select-Xml -RemoveNamespace
- # Version 5.0 Added Update-Xml to allow setting xml attributes or node content
- # Version 6.0 Major cleanup, breaking changes.
- # - Added Get-XmlContent and Set-XmlContent for loading/saving XML from files or strings
- # - Removed Path and Content parameters from the other functions (it greatly simplifies thost functions, and makes the whole thing more maintainable)
- # - Updated Update-Xml to support adding nodes "before" and "after" other nodes, and to support "remove"ing nodes
- # Version 6.1 Update for PowerShell 3.0
- # Version 6.2 Minor tweak in exception handling for CliXml
- # Version 6.3 Added Remove-XmlElement to allow removing nodes or attributes
- # This is something I specifically needed to remove "ignorable" namespaces
- # Specifically, the ones created by the Visual Studio Workflow designer (and perhaps other visual designers like Blend)
- # Which I don't want to check into source control, because it makes diffing nearly impossible
- # Version 6.4 Fixed a bug on New-XElement for Rudy Shockaert (nice bug report, thanks!)
- # Version 6.5 Added -Parameters @{} parameter to New-XDocument to allow local variables to be passed into the module scope. *grumble*
- function Add-Accelerator {
- <#
- .Synopsis
- Add a type accelerator to the current session
- .Description
- The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
- .Example
- Add-Accelerator list System.Collections.Generic.List``1
- $list = New-Object list[string]
- Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
- .Example
- Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
- $list = New-Object "list t[string]"
- Creates two accelerators for the Generic List[T] collection type.
- .Parameter Accelerator
- The short form accelerator should be just the name you want to use (without square brackets).
- .Parameter Type
- The type you want the accelerator to accelerate (without square brackets)
- .Notes
- When specifying multiple values for a parameter, use commas to separate the values.
- For example, "-Accelerator string, regex".
- PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
- Also see the help for Get-Accelerator and Remove-Accelerator
- .Link
- huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
- #>
- [CmdletBinding()]
- param(
- [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
- [Alias("Key","Name")]
- [string[]]$Accelerator
- ,
- [Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
- [Alias("Value","FullName")]
- [type]$Type
- )
- process {
- # add a user-defined accelerator
- foreach($a in $Accelerator) {
- if($xlr8r::AddReplace) {
- $xlr8r::AddReplace( $a, $Type)
- } else {
- $null = $xlr8r::Remove( $a )
- $xlr8r::Add( $a, $Type)
- }
- trap [System.Management.Automation.MethodInvocationException] {
- if($xlr8r::get.keys -contains $a) {
- if($xlr8r::get[$a] -ne $Type) {
- Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
- }
- Continue;
- }
- throw
- }
- }
- }
- }
- &{
- $local:xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
- $local:xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
- $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | Add-Accelerator
- Add-Accelerator "Dictionary" "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
- Add-Accelerator "PSParser" "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
- }
- function Get-XmlContent {
- #.Synopsis
- # Load an XML file as an XmlDocument
- param(
- # Specifies a string that contains the XML to load, or a path to a file which has the XML to load (wildcards are permitted).
- [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
- [ValidateNotNullOrEmpty()]
- [Alias("PSPath","Path")]
- [String[]]$Content
- ,
- # If set, loads XML with all namespace qualifiers removed, and all entities expanded.
- [Alias("Rn","Rm")]
- [Switch]$RemoveNamespace
- )
- begin {
- [Text.StringBuilder]$XmlContent = [String]::Empty
- [bool]$Path = $true
- }
- process {
- if($Path -and ($Path = Test-Path @($Content)[0] -EA 0)) {
- foreach($file in Resolve-Path $Content) {
- $xml = New-Object System.Xml.XmlDocument;
- if($file.Provider.Name -eq "FileSystem") {
- Write-Verbose $file.ProviderPath
- $xml.Load( $file.ProviderPath )
- } else {
- $ofs = "`n"
- $xml.LoadXml( ([String](Get-Content $file)) )
- }
- if($RemoveNamespace) {
- [System.Xml.XmlNode[]]$Xml = @(Remove-XmlNamespace -Xml $node)
- }
- Write-Output $xml
- }
- } else {
- # If the "path" parameter isn't actually a path, assume that it's actually content
- foreach($line in $content) {
- $null = $XmlContent.AppendLine( $line )
- }
- }
- }
- end {
- if(!$Path) {
- $xml = New-Object System.Xml.XmlDocument;
- $xml.LoadXml( $XmlContent.ToString() )
- if($RemoveNamespace) {
- $Xml = @(Remove-XmlNamespace -Xml $xml)
- }
- Write-Output $xml
- }
- }}
- Set-Alias Import-Xml Get-XmlContent
- Set-Alias ipxml Get-XmlContent
- Set-Alias ipx Get-XmlContent
- Set-Alias Get-Xml Get-XmlContent
- Set-Alias gxml Get-XmlContent
- Set-Alias gx Get-XmlContent
- function Set-XmlContent {
- param(
- [Parameter(Mandatory=$true, Position=1)]
- [Alias("PSPath")]
- [String]$Path
- ,
- # Specifies one or more XML nodes to search.
- [Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
- [ValidateNotNullOrEmpty()]
- [Alias("Node")]
- [Xml]$Xml
- )
- process {
- $xml.Save( $Path )
- }
- }
- Set-Alias Export-Xml Set-XmlContent
- Set-Alias epxml Set-XmlContent
- Set-Alias epx Set-XmlContent
- Set-Alias Set-Xml Set-XmlContent
- Set-Alias sxml Set-XmlContent
- Set-Alias sx Set-XmlContent
- function Format-Xml {
- #.Synopsis
- # Pretty-print formatted XML source
- #.Description
- # Runs an XmlDocument through an auto-indenting XmlWriter
- #.Parameter Xml
- # The Xml Document
- #.Parameter Path
- # The path to an xml document (on disc or any other content provider).
- #.Parameter Indent
- # The indent level (defaults to 2 spaces)
- #.Example
- # [xml]$xml = get-content Data.xml
- # C:\PS>Format-Xml $xml
- #.Example
- # get-content Data.xml | Format-Xml
- #.Example
- # Format-Xml C:\PS\Data.xml
- #.Example
- # ls *.xml | Format-Xml
- #
- [CmdletBinding()]
- param(
- [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")]
- [xml]$Xml
- ,
- [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
- [Alias("PsPath")]
- [string]$Path
- ,
- [Parameter(Mandatory=$false)]
- $Indent=2
- )
- process {
- ## Load from file, if necessary
- if($Path) { [xml]$xml = Get-Content $Path }
- $StringWriter = New-Object System.IO.StringWriter
- $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter
- $xmlWriter.Formatting = "indented"
- $xmlWriter.Indentation = $Indent
- $xml.WriteContentTo($XmlWriter)
- $XmlWriter.Flush()
- $StringWriter.Flush()
- Write-Output $StringWriter.ToString()
- }}
- Set-