首页 > 解决方案 > 如何使用 PowerShell 中的 XPath 表达式检测 XML 中的嵌套列表?

问题描述

我们使用 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>

标签: xmlpowershellodt

解决方案


# 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//LIXPath 查询,它只查找嵌套列表,自动覆盖<OL><UL>列表;原来的查询是:
//OL//UL | //UL//OL | //OL//OL | //UL//UL


推荐阅读