8

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.

Update

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);
}
1
  • Please show the input XML document. Commented Apr 21, 2015 at 19:02

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you are right, i needed to prefix each element with the namespace. It just seems a little strange, since its the default namespace.
No need for either a NamespaceManager nor using the prefix for each element, its just "/Project/ItemGroup/Reference" with $Ns = @{"ns"="schemas.microsoft.com/developer/msbuild/2003"} - at least with PowerShell version 5.1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.