xml - 如何使用 PowerShell 中的 XPath 表达式检测 XML 中的嵌套列表?
问题描述
我们使用 PowerShell 脚本和 XSLT 样式表在我们的客户网站上以 HTML 和 ODT 格式发布我们的发行说明。但是发行说明中的任何嵌套列表都不会呈现在 ODT 文件中。我们将告诉我们的技术作者不要再使用嵌套列表创建发行说明,但如果他们这样做了,我们希望我们的脚本在检测到任何嵌套列表时停止并返回错误。
如何编写一个 XPath 表达式(以添加到我们现有的 PowerShell 脚本)
- 停止发布脚本并
- 如果检测到任何嵌套列表(在发行说明的原始 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>
解决方案
# 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 查询,它只查找嵌套列表项,自动覆盖<OL>
和<UL>
列表;原来的查询是://OL//UL | //UL//OL | //OL//OL | //UL//UL
推荐阅读
- c# - WPF ScrollToTop 与 ScrollToHome
- php - 将复杂的 XML 反序列化为对象
- kubernetes - 无法使用 terraform cloud 在 Kubernetes 中创建秘密
- python-3.x - 基于“模式矩阵”的图像合成
- c++ - 使用全局变量 Cpp
- javascript - 如何在 Pug (Jade) 的“每个”迭代中使用 JavaScript 变量
- spring-boot - 我该如何解决Axon server Stream Error的问题
- office365 - 'DateTime' 没有发生 len()),与 Odoo 和 Zapier 集成
- reactjs - 更改图标启动器后 processDebugResources FAILED
- python - Kivy 视频播放器延迟/滞后