I have an xml file that contains elements with namespaces that I am wishing to read using PowerShell.
Example XML:
<ns0:Members xmlns:ns0="http://my.domain.com/subsite">
<Member>
<MemberDetails>
<Name>Blah de Blah Blah</Name>
<Email>blah@lost.com</Email>
</MemberDetails>
</Member>
</Members>
From some examples I found online, I wrote the following PowerShell to read the XML:
function Get-ScriptDirectory
{
return Split-Path $script:MyInvocation.MyCommand.Path
}
$xmlFile = Join-Path (Get-ScriptDirectory) "MyXmlFile.xml"
[xml]$xmlDoc = Get-Content $xmlFile
$ns = new-object Xml.XmlNamespaceManager $xml.NameTable
$ns.AddNamespace("ns0", "http://my.domain.com/subsite")
$node = $xmlDoc.SelectNodes("ns0:Members")
However, I get the following error:
New-Object : Constructor not found. Cannot find an appropriate constructor for type Xml.XmlNamespaceManager.
I searched online for the error but the only post I found suggested double-checking that the version of PowerShell was version 2.
I ran $Host.Version
, which gave me:
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
When I stepped through the script using PowerGui Editor, I discovered that $xml.NameTable
is null.
Can anyone explain why and what I can do to fix it?
On another note, none of the methods I've tried to select the Members
element has worked including Select-Xml
and $xmlDoc.SelectNodes
. The only way I could get it was using:
$xmlDoc.Members