簡體   English   中英

Powershell-XPath-SUM()和Count()子節點-僅XPath表達式

[英]Powershell - XPath - SUM() and Count() Child Nodes - XPath Expression Only

Xpath的新手,在powershell中處於中間。 昨天花了很多時間研究,但在powershell -XPath命令中找不到xpath sum()或count()表達式的單個示例。 我將這作為我的第一個stackoverflow問題來進行詳細介紹,以便將來的人們可以從XPert那里找到本文的清晰示例答案。

目標(2):1. Count()關鍵過程。 2. SUM()由關鍵流程處理的交易。
注意:powershell XPath命令的輸出應為原始數字。

<units>
<unit>
  <unitName>Generic Process Unit</unitName>
    <attribute>
      <name>Process Type</name>
      <value>Critical Process</value>
    </attribute>
    <attribute>
      <name>Transactions Processed</name>
      <value>10</value>
    </attribute>
</unit>

<unit>
  <unitName>Generic Process Unit</unitName>
    <attribute>
      <name>Process Type</name>
      <value>Trivial Process</value>
    </attribute>
    <attribute>
      <name>Transactions Processed</name>
      <value>7</value>
    </attribute>
</unit>

<unit>
  <unitName>Generic Process Unit</unitName>
    <attribute>
      <name>Process Type</name>
      <value>Critical Process</value>
    </attribute>
    <attribute>
      <name>Transactions Processed</name>
      <value>5</value>
    </attribute>
</unit>
</units>

我對SUM功能的最佳嘗試。 甚至沒有嘗試Count:

select-xml -path mine.xml -XPath '//attribute[value="Critical Process"]/../attribute[name="Transactions Processed"][sum(value)]' | Select-Object -ExpandProperty node | select Value

編輯:下面是從notepad ++ XMLTool插件工作的XPath,但仍需要Powershell等效項(這在Powershell中不起作用):

sum(//attribute[value="Critical Process"]/../attribute[name="Transactions Processed"]/value)

勘誤表:之所以需要僅XPath表達式,是因為我僅使用powershell構造和驗證我的XPath字符串。 最終目標是將這些字符串放入實際上將使用XPath字符串的非Powershell軟件中。 該軟件使我無法驗證XPath,將它放入后需要20分鍾的時間才能知道它是否可以工作,因此我將Powershell用作測試平台。

我更改了項目名稱,說明並刪除了屬性,以使示例更簡單。 但是,我不知道“ schema”一詞是否重要,因此這里是原始“ value”行的一個示例。

<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Critical Process</value>

問題:

  • 似乎需要對給定的XPath表達式進行一些調整才能在Powershell中工作。 例如,在-XPath'/ xpath / node'之后,您似乎總是需要以'/ text()'結尾。 選擇對象-ExpandProperty節點| 選擇“值”以實際查看所需的輸出。

  • Microsoft具有XPath文檔和Powershell文檔,但是沒有“ PowerShell中的XPath表達式”文檔。

  • 大多數Internet表達式的示例都使用“ Powershell + XPath”來做最少的XPath來獲取數據對象,然后在powershell中使用foreach進行循環。

  • 看起來命令語法可能與XPath版本1、2等有關。

提前致謝。

據我所知,這些功能不適用於Select-Xml因為它似乎在幕后只能使用返回節點的[XmlDocument] :: SelectNodes。

或者,您可以使用導航器:

$xml = @'
#your xml here
'@ -as [xml]

$xml.CreateNavigator().Evaluate('count(//unit)')
$xml.CreateNavigator().Evaluate('sum(//unit)')

計數應盡可能簡單

count(/units/unit[attribute[name="Process Type"][value="Critical Process"]])

(使用兩個嵌套的謂詞級別來確保namevalue都在同一 attribute )。 對於總和,我們只需在表達式的末尾添加一點

sum(/units/unit[attribute[name="Process Type"][value="Critical Process"]]/attribute[name="Transactions Processed"]/value)

但是請注意,這兩個表達式都將返回數字值,而不是節點集,這可能會使powershell感到困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM