简体   繁体   中英

selecting specific node with xpath in powershell

I am trying to select a specific node in an xml file for the purposes of comparing it to the same node in another file.

I can navigate through the file using the generic nodes, but I can't figure out how to get an exact Xpath.

Here's the XML:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- Domain wide values -->
  <PropertyGroup>
    <LoggingLevel>0</LoggingLevel>
    <LongTimeouts>0</LongTimeouts>
  </PropertyGroup>
  <ItemGroup>
    <!--AB-->
    <Token Include="{AB_ANALYTICSSERVER}">
      <Value>Test</Value>
    </Token>
    <Token Include="{AB_CERTFINDVALUE}">
      <Value>$(CertName)</Value>
    </Token>
    <Token Include="{AB_SERVICECERTFINDVALUE}">
      <Value>$(CertName)</Value>
    </Token>
    <Token Include="{AB_CONSUMERSGROUP}">
      <Value>DLG-AB-users</Value>
    </Token>
    <!--AB End-->
    <!--Database-->
    <Token Include="{Database_Domain}">
      <Value>$(Domain)</Value>
    </Token>
    <Token Include="{Audit_Domain}">
      <Value>$(Domain)</Value>
    </Token>
    <!--Database End-->
  </ItemGroup>
</Project>

But I am clearly missing something in my xpath based queries:

eg $xmlNew.SelectNodes("/node()[1]/node()[3]/node()[2]").outerxml

Returns:

<Token Include="{AB_ANALYTICSSERVER}" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><Value>Test</Value></Token>

But neither of these return anything:

$xmlNew.SelectNodes("/Project/ItemGroup/Token").outerxml

$xmlnew.selectnodes('//token[contains(@Include,"{AB_ANALYTICSSERVER}")]').OuterXml

Similarly this works:

$xmlNew.SelectNodes("/node()[1]/node()[2]/node()[2]").outerxml

but this doesn't:

$xmlnew.selectnodes('/Project/PropertyGroup/LongTimeouts').outerxml doesnt.

What obvious thing am i missing? :/

Thanks

The problem is that your XPath isn't valid because of the namespace.

You can abuse PowerShell's power however and simply access Token as if it was an object structure.

$xmlNew.Project.ItemGroup.Token.outerxml

You can also use Select-Xml cmdlet and specify the namespace explicitly with your XPath as it is shown in this answer .

$ns = @{dns = 'http://schemas.microsoft.com/developer/msbuild/2003'}
Select-Xml -Xml $xmlNew -XPath '//dns:Token' -Namespace $ns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM