【发布时间】:2017-03-16 08:51:10
【问题描述】:
如果我使用变量作为 XML 中元素的路径,我很难读取其中包含 CDATA 的 XML 文件。 (注意:这是基于How to read CDATA in XML file with PowerShell?)
在 $xmlsource 文件中
<list>
<topic>
<SubTopic>
<topicTitle>Test</topicTitle>
<HtmlHead><![CDATA[<br>randomHTMLhere</br>]]></HtmlHead>
</SubTopic>
<SubTopic2>
<topicTitle>Test2</topicTitle>
<HtmlHead><![CDATA[<br>randomHTMLhere2</br>]]></HtmlHead>
</SubTopic2>
</topic>
</list>
在 PowerShell 中
[String]$xmlsource = "C:\PowerShell_scripts\xmlsource.xml"
[xml]$XmlContent = get-content $xmlsource
#These methods work but the Paths are HARD-CODED
Write-host "`r`nUsing HARD-CODED Paths"
$XmlContent.list.topic.SubTopic.HtmlHead.'#cdata-section'
$XmlContent.list.topic.SubTopic.HtmlHead.InnerText
$XmlContent.list.topic.SubTopic2.HtmlHead.InnerText
#But if the path is given in a variable, I get nothing.
Write-host "`r`nUsing `$pathToElement (returns blank line)"
[String]$pathToElement = 'list.topic.SubTopic.HtmlHead'
$XmlContent.$pathToElement.InnerText #This return a blank line
#Insult to injury
#This kinda works but to parse the path to fit in the 'GetElementsByTagName' method would be clunky, inflexible and would still return the CDATA from *both* 'HtmlHead' elements.
Write-host "`r`nwith GetElementsByTagName(`$var)"
[String]$ElementName= 'HtmlHead'
$XmlContent.GetElementsByTagName($ElementName).'#cdata-section'
Write-host "`r`nwith GetElementsByTagName()"
$XmlContent.GetElementsByTagName('HtmlHead').'#cdata-section'
是否需要将 $pathToElement 转换为特殊数据类型?
注意:Xpath 是一种 XML 查询语言,所以我更正了上面的问题。
【问题讨论】:
标签: xml powershell xpath cdata