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

571 views Asked by At

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.

1

There are 1 answers

1
Nicholas Saunders On

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.