如何使用PowerShell使用XML路径的变量读取XML文件中的CDATA?

时间:2016-11-02 21:31:16

标签: xml powershell xpath cdata

如果我使用变量作为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的查询语言所以我更正了上面的问题。

1 个答案:

答案 0 :(得分:2)

$XmlContent.list.topic.SubTopic.HtmlHead 

正在查找名为list的属性,然后从该返回值查找'topic',然后从该返回值...等等。

$XmlContent.$XpathToElement

正在尝试查找名为list.topic.SubTopic.HtmlHead的单个属性而未找到它。

我不认为'list.topic.SubTopic.HtmlHead'是XPath表达式的正确形式。你可以这样做:

$node = Select-Xml -xml $XmlContent -XPath '/list/topic/SubTopic/HtmlHead' | select -expand node
$node.InnerText

编辑:并执行

Select-Xml -xml $xml -XPath '/list/topic//HtmlHead'

获取SubTopic和SubTopic2的HtmlHeads。

自我生成的PS帮助链接来自我的代码块(如果有):

  • Select-Xml(在模块Microsoft.PowerShell.Utility中)
  • selectSelect-Object的别名(在模块Microsoft.PowerShell.Utility中)