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

筅森魡賤 提交于 2021-01-29 08:10:38

问题


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:


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.



来源:https://stackoverflow.com/questions/65234296/how-to-parse-xml-in-powershell-with-select-xml-and-xpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!