I have an XML document that contains two namespaces (the 'default' namespace and xlink):
- xmlns="http://embassy/schemas/dudezilla/"
- xmlns:xlink="http://www.w3.org/1999/xlink"
How do I specify "both" namespaces in my PowerShell code? PowerShell seems to want a prefix for the default namespace. How do I do this?
Right now I have the following code (not sure what to include for the default namespace):
[System.Xml.XmlNamespaceManager] $nsmgr = $xml.NameTable;
$nsmgr.AddNamespace('?','http://embassy/schemas/dudezilla/');
[System.Xml.XmlNamespaceManager] $nsmgr = $开发者_如何转开发xml.NameTable;
$nsmgr.AddNamespace('xlink','http://www.w3.org/1999/xlink');
[System.Xml.XmlNodeList] $nodelist;
[System.Xml.XmlElement] $root = $xml.DocumentElement;
$nodelist = $root.SelectNodes("//image/@xlink:href", $nsmgr);
Foreach ($xmlnode in $nodelist)
{
$xmlnode.Value;
}
Thanks!
PowerShell v2 makes this simpler:
$ns = @{
dns="http://embassy/schemas/dudezilla/"
xlink="http://www.w3.org/1999/xlink"
}
$xml | Select-Xml '//dns:image/@xlink:href' -Namespace $ns
If you want to do it the other way try:
$nsmgr = New-Object System.Xml.XmlNamespaceManager $xml.NameTable
$nsmgr.AddNamespace('dns','http://embassy/schemas/dudezilla/')
$nsmgr.AddNamespace('xlink','http://www.w3.org/1999/xlink')
$root = $xml.DocumentElement
$nodelist = $root.SelectNodes("//dns:image/@xlink:href", $nsmgr)
foreach ($xmlnode in $nodelist)
{
$xmlnode.Value
}
Figured it out. Had to use $null for the prefix of the default namespace ($null is equivalent to String.Empty in C#).
Working code:
[System.Xml.XmlNamespaceManager] $nsmgr = $xml.NameTable;
$nsmgr.AddNamespace($null,'http://embassy/schemas/dudezilla/');
$nsmgr.AddNamespace('xlink','http://www.w3.org/1999/xlink');
[System.Xml.XmlNodeList] $nodelist;
[System.Xml.XmlElement] $root = $xml.DocumentElement;
$nodelist = $root.SelectNodes("//image/@xlink:href", $nsmgr);
Foreach ($xmlnode in $nodelist)
{
$xmlnode.Value;
}
精彩评论