如何解决结合使用XSLT和正则表达式来查找字符串
我正在尝试找到一种识别XML文件中特定字符串,标点符号和类似字符的方法,这些字符串有时必须出现在特定元素中,有时不是。 IOW有时我想忽略<command>
或<screen>
或其他元素。
示例源XML:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % common_entities SYSTEM "../../../common.ent">
%common_entities;
]>
<section>
<title>Summary</title>
<para>Sample file.</para>
<itemizedlist>
<listitem>
<para>No issues at all.</para>
</listitem>
<listitem>
<para>Contains a command,<command>cd ../</command>,which contains valid orphan punctuation.</para>
</listitem>
<listitem>
<para>Contains,random punctuation . in strange places,that should be identified.</para>
</listitem>
</itemizedlist>
<screen><prompt>[user@demo ~]$ </prompt><userinput>openstack,volume snapshot delete 53d27-2c10</userinput></screen>
<para>
The above screen element contains an orphan comma that should be ignored.
</para>
</section>
@MichaelKay的XSL(我添加了标题信息):
<?xml version="1.0"?>
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<!-- Match errors -->
<xsl:template match="entry/text()[matches(.,'\s[.,:;?!]')]"
mode="look-for-bad-punctuation" priority="5">
<bad-punctuation-found/>
</xsl:template>
<!-- Match unchecked elements -->
<xsl:template match="screen/text() | command/text()"
mode="look-for-bad-punctuation" priority="6">
<xsl:copy-of select="."/>
</xsl:template>
<!-- Match elements with no error -->
<xsl:template match="text()"
mode="look-for-bad-punctuation" priority="4">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
预期输出:
发现标点符号错误:包含
发现标点符号错误:随机标点符号。 等
如果它可以引用行号,那么效果很好。
此刻我得到的只是源文件的全文,减去所有DocBook元素,例如: 这句话包含一个命令cd ../,其中包含有效的孤立标点符号。
我正在使用saxon-he-10.1。
解决方法
您的样式表包含必要的规则,但是缺少要求应用规则的代码。只需添加
<xsl:template match="/">
<xsl:apply-templates select="//text()" mode="look-for-bad-punctuation"/>
</xsl:template>
您还需要对专门处理的元素进行一些微调,例如屏幕/命令/提示/用户输入。
对于行号,Saxon-PE及更高版本提供扩展功能saxon:line-number()
-还需要在命令行上使用-l启用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。