Search code examples
powershellescaping

Escaping a colon in powershell


I have the following piece of code in Powershell trying to read back a piece of XML.

$path = "C:\path\8429006775491.xml"
$xml = [xml](Get-Content $path)
$xml.ern:NewReleaseMessage

The problem is the colon. I've tried to escape it with ' but it doesn't seem to work. Also tried to put it in {}

If I edit the colon in the XML file itself and change the code accordingly it reads back fine but unfortunately that is not an option.


Solution

  • In order for .NET to understand the namespace prefixes, you'll need a Namespace Manager object:

    $path = "C:\path\8429006775491.xml"
    $xml = [xml](Get-Content $path)
    
    $XmlNSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable
    $XmlNSManager.AddNamespace('ern','http://ddex.net/xml/ern/341')
    $XmlNSManager.AddNamespace('xsi','http://www.w3.org/2001/XMLSchema-instance')
    
    # Now you can use SelectNodes() with your namespace manager:
    
    # If NewReleaseMessage is the root node
    $xml.SelectNodes('/ern:NewReleaseMessage',$XmlNSManager)
    
    # If NewReleaseMessage is a descendant of the root node
    $xml.SelectNodes('//ern:NewReleaseMessage',$XmlNSManager)