问题
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. Any help really appreciated.
回答1:
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)
来源:https://stackoverflow.com/questions/31724250/escaping-a-colon-in-powershell