【问题标题】:Xpath in PowerShell: Display result in two columnsPowerShell 中的 Xpath:在两列中显示结果
【发布时间】:2021-01-07 00:26:27
【问题描述】:

我将以这个示例数据为例:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>

数据链接:https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)

假设我想查询作者和价格

[xml]$XmlFileObj = Get-Content 'C:\Users\David\Documents\XmlSample.dtsx'

$XmlFileObj | Select-Xml -XPath "/catalog/book/author | /catalog/book/price "  | Select-Object -ExpandProperty Node

结果是:

#text               
-----               
Gambardella, Matthew
44.95               
Ralls, Kim          
5.95   

如果我希望结果看起来像:

#col1; col2               
-----               
Gambardella, Matthew; 44.95               
Ralls, Kim ; 5.95   

或者类似的表格形式...

【问题讨论】:

    标签: xml powershell xpath


    【解决方案1】:

    不要分别提取&lt;author&gt;&lt;price&gt;节点,而是使用Select-Xml枚举共同祖先——&lt;book&gt;节点——然后直接从每个节点中选择作者和价格节点:

    $XmlFileObj |Select-Xml '/catalog/book' |Select -ExpandProperty Node |Select author,price
    

    如果您想根据后代节点值进行过滤,您可以使用 XPath 谓词 (//node/selector[predicate goes here]):

    # This will return the author and price, but only of "Midnight Rain" 
    $XmlFileObj |Select-Xml '/catalog/book[genre = "Fantasy"]' |Select -ExpandProperty Node |Select author,price
    

    如果您找不到合适的 XPath 函数或运算符,您还可以利用 PowerShell 的内置 XML 适配器,就像我们从 Select-Object (或任何其他 cmdlet 的)透视图,它们的属性就像在任何其他对象上一样:

    # This will return the author and price, but only of "Midnight Rain" 
    $XmlFileObj |Select-Xml '/catalog/book' |Select -ExpandProperty Node |Where genre -eq Fantasy |Select author,price
    

    【讨论】:

    • 太好了,谢谢。我在哪里可以阅读更多相关信息,我应该搜索什么?
    • @David 关于什么? XPath?
    • 是 PowerShell 中的 Xpath,通常还有 PowerShell。
    • @David 不确定除了“Select-Xml 允许您使用 XPath 选择器来选择 XML 文档的元素”之外还有很多其他的东西。这里要吸取的基本教训基本上是“如果你想保留它们的关系,不要将关系数据拆分成不相交的部分”——这非常普遍地适用于 PowerShell,而不仅仅是在 XPath/XML 的上下文中:)
    • @David 很抱歉含糊不清,Select Select-Object - Select 只是一个别名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2014-10-28
    • 2013-01-15
    • 2014-02-16
    相关资源
    最近更新 更多