Search code examples
xmlpowershellvisual-studioxpath

Parsing the XML in Powershell: Escaping various symbols in XPath


I need to parse the VS2022 .vbproj file to find the details of build configuration. In powershell, I load the file and try to get to the necessary node. But I'm stuck with misleading PS error reporting and overwhelming amount of special symbols to escape...

I am looking for that line from .vbproj:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

here is my script:

$xml = [xml](Get-Content $xmlFile)

$propertyGroup = $xml.SelectSingleNode("//PropertyGroup[@Condition= ""''`$(Configuration)|`$(Platform)'' == ''Debug|AnyCPU''""]")
if ($propertyGroup) {
    Write-Host 'Element found.'
} else {
    Write-Host 'Element not found.'
}

Whatever I do, I either get either syntax errors, or "Element not found"... Please help!


Solution

  • Use :

    $xml.SelectSingleNode("//PropertyGroup[normalize-space(translate(@Condition,`"'$`",`"`"))='(Configuration)|(Platform) == Debug|AnyCPU']")
    

    We escape " and $ characters and use translate function to do it only once.

    Another option with contains and no escaping :

    $xml.SelectSingleNode("//PropertyGroup[contains(@Condition,'(Configuration)') and contains(@Condition,'(Platform)') and contains(@Condition,'Debug') and contains(@Condition,'AnyCPU')]")