简体   繁体   中英

Selecting value of an element in xml using xpath in powershell

I want to have the value for element RN (so, 20200121) (i found an example here and modified it)

XML 图像

file is located at d:\test.xml

I tried:

[xml] $xdoc =  get-content “d:\test.xml”  
$xdoc |  Select-Xml “//RN.value” |  % { $_.Node.InnerText } |  select  -Unique

Which fails with error

Select-Xml : Cannot validate argument on parameter 'Xml'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:1 char:10
+ $xdoc |  Select-Xml “//RN” |  % { $_.Node.InnerText } |  select   ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Select-Xml], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SelectXmlCommand

I also tried:

[xml] $xdoc =  get-content “d:\test.xml”
$xdoc |  Select-Xml “//RN.value” |  % { $_.Node.InnerText } |  select  -Unique

which gives no error nor output

This seems to be a namespace resolution issue:

$values = $xdoc |Select-Xml '//top:RN/top:value' -Namespace @{top='http://www.test.int'}|%{$_.Node.InnerText} |Select -Unique

That should do the trick

There are various ways to not refer to the namespaces: how to ignore namespaces with XPath

$xdoc.message.bamessage.rn.value

20200121


select-xml '//*[local-name()="value"]' test.xml | % node

#text
-----
20200121

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