How to parse XML in Powershell with Select-Xml and Xpath?
Asked Answered
R

1

0

obvious output for this example would be the date and time.


In the context of iterating over an xml document, how is this document correctly cast or converted to xml in Powershell dotnet core on Linux?

PS /home/nicholas/flwor> 
PS /home/nicholas/flwor> Select-Xml -Xml (Get-Date | ConvertTo-Xml) -XPath "/Objects/Object"

Node   Path        Pattern
----   ----        -------
Object InputStream /Objects/Object

PS /home/nicholas/flwor> 
PS /home/nicholas/flwor> (Get-Date | ConvertTo-Xml).OuterXml                                
<?xml version="1.0" encoding="utf-8"?><Objects><Object Type="System.DateTime">12/10/2020 5:12:45 AM</Object></Objects>
PS /home/nicholas/flwor> 

updated with the simplest possible example.

So, this example is xml but: how is it parsed or queried with xpath?

alternate solution given in IRC:

PS /home/nicholas/flwor> 
PS /home/nicholas/flwor> $date.SelectSingleNode('/Objects/Object').'#text'
12/10/2020 5:07:04 AM
PS /home/nicholas/flwor> 

no doubt that's doable with Select-Xml and Xpath.

Rawalpindi answered 10/12, 2020 at 12:13 Comment(1)
Use quotes: $serviceStatePath = './serviceState.xml' or use a named (-Path) parameter.Collectivism
R
0

if awkward, this works:

PS /home/nicholas/flwor> 
PS /home/nicholas/flwor> Select-Xml -Xml (Get-Date | ConvertTo-Xml) -XPath "/Objects/Object" |  Select-Object -ExpandProperty Node

Type            #text
----            -----
System.DateTime 12/10/2020 5:23:39 AM

PS /home/nicholas/flwor> 

the help files had a similar example.

Rawalpindi answered 10/12, 2020 at 13:25 Comment(1)
Returns date value directly: (Get-Date | ConvertTo-Xml | Select-Xml "/Objects/Object").Node.InnerTextGrain

© 2022 - 2024 — McMap. All rights reserved.