簡體   English   中英

在Powershell中解析HTML實體

[英]Parse html entities in Powershell

我正在通過Powershell使用Microsoft Team Foundation Server。 我要做的任務是為“測試用例”類型的給定工作項獲取並設置“步驟”。

出於某種我不知道的原因,TFS將諸如HTML之類的信息存儲在XML內 ,其中HTML元素是使用HTML實體編寫的,以便不弄亂XML。

這是一個例子:

<steps id="0" last="3">
    <step id="2" type="ValidateStep">
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;P&gt;I do this and that&lt;/P&gt;&lt;/DIV&gt;
        </parameterizedString>
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;
        </parameterizedString>
        <description/>
    </step>
    <step id="3" type="ActionStep">
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;DIV&gt;&lt;P&gt;I do something else &lt;BR/&gt;&lt;/P&gt;&lt;/DIV&gt;&lt;/DIV&gt;
        </parameterizedString>
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;P&gt;This happens &lt;BR/&gt;&lt;/P&gt;&lt;/DIV&gt;
        </parameterizedString>
        <description/>
    </step>
</steps>

顯示為: TFS如何呈現測試用例步驟的屏幕截圖

我如何獲得每個項目的“裸文本”? 例如, This happens&lt;DIV&gt;&lt;P&gt;This happens &lt;BR/&gt;&lt;/P&gt;&lt;/DIV&gt; 我需要編寫自己的解析器還是已經可以使用?

System.Web命名空間中可以幫助您的一些事情:

PS> add-type -AssemblyName system.web
PS> [System.Web.HttpUtility]::HtmlDecode("Baskin &amp; Robbins")
Baskin & Robbins

更新

我再次閱讀了您的問題,而您還想要更多。 如果您不熟悉xml和html語義,這會有些棘手,因此這里有一個腳本供我參考。 希望您可以根據需要進行修改。

add-type -AssemblyName system.web

$raw = @'
<steps id="0" last="3">
    <step id="2" type="ValidateStep">
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;P&gt;I do this and that&lt;/P&gt;&lt;/DIV&gt;
        </parameterizedString>
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;
        </parameterizedString>
        <description/>
    </step>
    <step id="3" type="ActionStep">
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;DIV&gt;&lt;P&gt;I do something else &lt;BR/&gt;&lt;/P&gt;&lt;/DIV&gt;&lt;/DIV&gt;
        </parameterizedString>
        <parameterizedString isformatted="true">
            &lt;DIV&gt;&lt;P&gt;This happens &lt;BR/&gt;&lt;/P&gt;&lt;/DIV&gt;
        </parameterizedString>
        <description/>
    </step>
</steps>
'@

$xml = [xml]$raw

$xml.steps.step | foreach-object { 
  write-host ('Processing {0}...' -f $_.type)

  $_.parameterizedString | foreach-object {
    # decode html entities
    $html = [System.Web.HttpUtility]::HtmlDecode($_.innerText)

    # let's hope the html is balanced and valid xhtml (matching begin/end tags)
    # assumption is that the innermost <P> wraps the desired text
    # match with xpath
    $text = ([xml]$html).SelectSingleNode('//P/text()').value

    write-host "Text: '$text'"
  }
}

暫無
暫無

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

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