如何在PowerShell中使用XPath表达式检测XML中的嵌套列表?

时间:2019-02-21 03:38:29

标签: xml powershell odt

我们使用PowerShell脚本和XSLT样式表在客户网站上以HTML和ODT格式发布发行说明。但是发行说明中的​​任何嵌套列表都不会呈现在ODT文件中。我们将告诉我们的技术作者不要再创建带有嵌套列表的发行说明,但如果这样做,我们希望脚本停止并在检测到任何嵌套列表时返回错误。

如何编写一个XPath表达式(添加到我们现有的PowerShell脚本中)

  1. 停止发布脚本
  2. 如果检测到任何嵌套列表(在发行说明的原始xml中),则会返回错误?

例如,下面的发行说明xml在编号列表()中嵌套了一个项目符号列表()。我想在我们的PowerShell脚本中添加一些内容以检测到此情况以及所有其他嵌套列表情况(OL中的OL,UL中的UL,UL中的OL)。

<shortDescription>Pricing Platform</shortDescription>
<note><P>We've added these new features:</P>
<P>
 <OL>
  <LI>A new Summary Report.</LI>
  <LI>Price Scheme page: We've added a mandatory priority setting to the Price Scheme page.</LI>
  <LI>A new Management page, where you can edit each screen's type.</LI>
  <LI>The following search criteria have been added to the Pricing page:
   <UL>
    <LI>name</LI>
    <LI>cinema</LI>
    <LI>status</LI>
   </UL>
  </LI>
</OL>

1 个答案:

答案 0 :(得分:0)

# Sample document.
$xmlDoc = [xml] @'
<xml>
<shortDescription>Pricing Platform</shortDescription>
<note><P>We've added these new features:</P>
<P>
 <OL>
  <LI>A new Summary Report.</LI>
  <LI>Price Scheme page: We've added a mandatory priority setting to the Price Scheme page.</LI>
  <LI>A new Management page, where you can edit each screen's type.</LI>
  <LI>The following search criteria have been added to the Pricing page:
   <UL>
    <LI>name</LI>
    <LI>cinema</LI>
    <LI>status</LI>
   </UL>
  </LI>
</OL>
</P>
</note>
</xml>
'@

#'# Execute an XPath query that looks for nested lists of either type
# in any combination, anywhere in the document hierarchy.
# If it returns at least one node, $hasNestedLists will contain $true.
$hasNestedLists = [bool] (Select-Xml -Xml $xmlDoc -XPath '//LI//LI')

if ($hasNestedLists) { Throw "Nested lists found." }

Michael Kay的提示,以提供更简单的//LI//LI XPath查询,该查询只查找嵌套列表项目,该列表自动覆盖了两个{{ 1}}和<OL>列表;原始查询是:
<UL>