[英]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">
<DIV><P>I do this and that</P></DIV>
</parameterizedString>
<parameterizedString isformatted="true">
<DIV><P>&nbsp;</P></DIV>
</parameterizedString>
<description/>
</step>
<step id="3" type="ActionStep">
<parameterizedString isformatted="true">
<DIV><DIV><P>I do something else <BR/></P></DIV></DIV>
</parameterizedString>
<parameterizedString isformatted="true">
<DIV><P>This happens <BR/></P></DIV>
</parameterizedString>
<description/>
</step>
</steps>
顯示為:
我如何獲得每個項目的“裸文本”? 例如, This happens
在<DIV><P>This happens <BR/></P></DIV>
。 我需要編寫自己的解析器還是已經可以使用?
System.Web
命名空間中可以幫助您的一些事情:
PS> add-type -AssemblyName system.web
PS> [System.Web.HttpUtility]::HtmlDecode("Baskin & Robbins")
Baskin & Robbins
更新
我再次閱讀了您的問題,而您還想要更多。 如果您不熟悉xml和html語義,這會有些棘手,因此這里有一個腳本供我參考。 希望您可以根據需要進行修改。
add-type -AssemblyName system.web
$raw = @'
<steps id="0" last="3">
<step id="2" type="ValidateStep">
<parameterizedString isformatted="true">
<DIV><P>I do this and that</P></DIV>
</parameterizedString>
<parameterizedString isformatted="true">
<DIV><P>&nbsp;</P></DIV>
</parameterizedString>
<description/>
</step>
<step id="3" type="ActionStep">
<parameterizedString isformatted="true">
<DIV><DIV><P>I do something else <BR/></P></DIV></DIV>
</parameterizedString>
<parameterizedString isformatted="true">
<DIV><P>This happens <BR/></P></DIV>
</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.