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 is perfectley valid, I have tried without the default namespace xmlns="http://schemas.microsoft.com/developer/msbuild/2003" in the xml and its working fine.
I understand that I have to map the default namespace to an URI and use this to query the XML with this mapping, but I can't seem to get it to work.
How do I query the XML with a default namespace?, I havent been able to find anything usable on Google yet.
Working 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);
}
I can't be 100% sure without looking at the actual XML document (or representative sample of it). Anyway, it is often due to lack of namespace prefix usage in the xpath.
Note that in the case of default namespace, not only the element where default namespace declared, but also all of it's descendants are considered in the same namespace*. I'd suggest to try the following xpath :
/ns:Project/ns:ItemGroup/ns:Reference
*: except of explicit prefix usage in the descendant element, or other default namespace declared in descendant level (in a more local scope).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With