XPath and Powershell - Default Namespace

I have the following PowerShell function:

function getProjReferences([string] $projFile) { # Returns nothing $Namespace = @{ ns = "http://schemas.microsoft.com/developer/msbuild/2003"; }; $Xml = Select-Xml -Path $projFile -Namespace $Namespace -XPath "//ns:Project/ItemGroup/Reference" # Returns nothing [xml] $xml = Get-Content -Path $projFile [System.Xml.XmlNamespaceManager] $nsMgr = New-Object -TypeName System.Xml.XmlNamespaceManager($xml.NameTable) $nsMgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003"); [XmlNode] $nodes = $xml.SelectNodes("/ns:Project/ItemGroup/Reference", $nsMgr); } 

Both attempts return nothing, although the XPath query works fine, I tried without the default namespace xmlns = "http://schemas.microsoft.com/developer/msbuild/2003" in xml and its performance.

I understand that I need to map the default namespace to a URI and use it to query the XML with this mapping, but I cannot get it to work.

How can I request XML with a default namespace? I have not yet been able to find anything that can be used on Google.

Update

Work code:

 function getProjReferences([string] $projFile) { [xml] $xml = Get-Content -Path $projFile [System.Xml.XmlNamespaceManager] $nsMgr = New-Object -TypeName System.Xml.XmlNamespaceManager($xml.NameTable) $nsMgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003"); [XmlNode] $nodes = $xml.SelectNodes("/ns:Project/ns:ItemGroup/ns:Reference", $nsMgr); } 
+5
source share
1 answer

I cannot be 100% sure without looking at the actual XML document (or representative sample). Anyway, this is often due to the lack of using the namespace prefix in xpath.

Note that in the case of the default namespace, not only the element in which the default namespace is declared is considered, but all its descendants are considered in the same namespace *. I suggest trying the following xpath:

 /ns:Project/ns:ItemGroup/ns:Reference 

*: except for the use of an explicit prefix in an element of a descendant or other default namespace declared at the descendant level (in a more local area).

+3
source

All Articles