使用 XSLT 2.0/3.0 使用多个步骤将 CDATA 中的纯文本解析为 html。那里的一部分

Posted

技术标签:

【中文标题】使用 XSLT 2.0/3.0 使用多个步骤将 CDATA 中的纯文本解析为 html。那里的一部分【英文标题】:Parsing plain text in CDATA to html with XSLT 2.0/3.0 using multiple steps. Part way there 【发布时间】:2018-01-06 13:09:53 【问题描述】:

我有一个使用 XSLT 2.0/3.0 的工作流程,它使用支持 XSLT 3.0 的 Saxon-HE 最新版本,它将 XML 文件中的 CDATA 部分的文本标记为 html。该文本没有 HTML 标记,但有最少的纯文本标记,它依赖于新行和行首方括号中的标记。工作过程(此处未显示)使用在变量中设置文本的多个阶段,使用具有模式和大量<>' 等的替换函数逐渐进入最后一步。它不仅难以阅读,而且如果我想对标记添加另一个更改,它的可扩展性也不是很好。我已经开始尝试在下面构建一个更好的标记过程,但被卡住了。

这是我修剪后的 XML 文件结构的一个小示例:

<?xml version="1.0" encoding="UTF-8"?>
<project>
---------------------------------------------------
<document>
<docText><![CDATA[
[page 001] 1
[margin] Person1 to Person2
This Indenture made this x''th Day of y in the year z Between person1,     grantor, of place1 to person2, grantee, of place2 for 5 dollars ... the s''d person1 to s''d person2 ... signed under my hand.

Witnesses present
[signed] Mrs. Jane Doe (seal)
[witness] Mr. Witness1
[witness] Ms. Witness1

Court office month x''th year
I do hereby certify that ... and is thereon truly admitted to Record
[clerk] John G. Reynolds DCCC
]]></docText>
<persons>
<person role="grantor">Jane Doe</person>
<person role="grantee">Bob Jones</person>
</persons>
</document>
---------------------------------------------------
<document>
<docText><![CDATA[
[page 002] 2
[margin] Person3 to Person4
This Indenture made this x''th Day of y in the year z Between person1, grantor, of place1 to person2, grantee, of place2 for 5 dollars ... the s''d person1 to s''d person2 ... signed under my hand.

Witnesses present
[signed] Mr. John Doe (seal)
[witness] Mr. Witness1
[witness] Ms. Witness1

[page 003] 3

Court office month x''th year
I do hereby certify that ... and is thereon truly admitted to Record
[clerk] John G. Reynolds DCCC
]]></docText>
<persons>
<person role="grantor">John Doe</person>
<person role="grantee">Bob Jones</person>
</persons>
</document>
</project>

这些是我想对 CDATA 中的文本采取的一些步骤

    使用 \n 新行标记所有行 以方括号中的单词开头的行(例如,[witness])使用括号中的类(例如,&lt;div class="witness"&gt;rest of line&lt;/div&gt;)标记为&lt;div&gt; 剩余的行用&lt;p&gt;标签标记 所有空行都被删除 扫描上面&lt;div&gt;&lt;p&gt;文本节点中的文本以进行进一步处理: 找到任意一对单引号(即成对的撇号)后跟 1 到 4 个大写或小写字母,并放入 &lt;sup&gt;&lt;/sup&gt;(例如,25''th 变为 25&lt;sup&gt;th&lt;/sup&gt;

    将相邻的具有相同类名的&lt;div&gt;分组到外部的某个名称的&lt;div&gt;中,例如

    <div class="a">b</div>
    <div class="a">b</div>
    becomes
    <div class="a-outer">
    <div class="a">b</div>
    <div class="a">b</div>
    </div>
    
    根据需要添加其他标记。

我通过第 6 步(第 5 步的一半)得到了我想要的东西,尽管结构可能很差。这个样式表有效,并为我提供了我在更长的以前的样式表和模板中所拥有的大部分内容。

这是我的 XSLT 3.0 样式表和模板的简化版本:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" 
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns:my="my:functions" 
xmlns:fn="http://www.w3.org/2005/xpath-functions"
exclude-result-prefixes="xsl xs my fn" expand-text="yes">

<xsl:output method="html" html-version="5.0" encoding="utf-8"  indent="yes"/>
<xsl:template match="/">
<html>
      <head>
      <title>Test Title</title>
      <style>
    div background-color: pink;
    p background-color: ; clear: right; margin-bottom: 0;
    .clerk, .signed float:right;
    .margin::before content: "[margin note:] ";
    .clear clear: right;
      </style>
      </head>
      <body>
           <h2>Records</h2>
           <xsl:apply-templates select="project/document"/>
      </body>
 </html>
 </xsl:template>

 <xsl:template match="document">
      <article>
      <h3><xsl:value-of select="persons/person[@role='grantor']"/> to 
      <xsl:value-of select="persons/person[@role='grantee']"/></h3>
      <xsl:apply-templates select="docText"/> <!-- docText contains text inside CDATA section -->
      <div class="clear"/>
      </article><hr />
 </xsl:template>

 <!-- all lines of text are parsed here and tagged with either <p> or  <div> and blank lines discarded-->
<xsl:template match="docText">
<xsl:variable name="vLines" select="fn:analyze-string(., '\n')" />
<xsl:for-each select="$vLines/fn:non-match">
<xsl:choose>
<xsl:when test="starts-with(.,'[')">
    <xsl:variable name="v2" select="fn:analyze-string(.,'\[(witness|signed|clerk|margin)\]')"/>
    <div class="fn:replace($v2/fn:match , '\[(.*?)\]' , '$1')">$v2/fn:non-match</div>
</xsl:when>
<xsl:otherwise>
    <p>
    <xsl:call-template name="tReplaceDblApos">
    <xsl:with-param name="pText" select="."/>
    </xsl:call-template>
    </p>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>

 <!-- any 1 to 4 characters following two adjacent single quotes is tagged with <sup> without quotes-->
 <xsl:template name="tReplaceDblApos">
 <xsl:param name="pText"/>
 <xsl:analyze-string select="$pText" regex="''([a-zA-Z]1,4)">
 <xsl:matching-substring>
      <sup><xsl:value-of select="regex-group(1)"/></sup>
 </xsl:matching-substring>
 <xsl:non-matching-substring>
      <xsl:value-of select="."/>
 </xsl:non-matching-substring>
 </xsl:analyze-string>
 </xsl:template>

 </xsl:stylesheet>

对于完成此类标记的更好方法以及如何使其可扩展并完成例如列出的最后一步的任何建议,我将不胜感激。在过去的几个月里,我已经尝试过让这个过程更简单,这是迄今为止我得到的最接近的。 对任何滥用术语、长示例和代码的新手状态表示歉意。

迈克尔

【问题讨论】:

【参考方案1】:

这里尝试直接在使用tokenize 函数标记的行上进行分组:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="xs math mf"
    version="3.0">

    <xsl:output method="html" html-version="5.0" encoding="utf-8"  indent="yes"/>
    <xsl:template match="/">
        <html>
            <head>
                <title>Test Title</title>
                <style>
                    div background-color: pink;
                    p background-color: ; clear: right; margin-bottom: 0;
                    .clerk, .signed float:right;
                    .margin::before content: "[margin note:] ";
                    .clear clear: right;
                </style>
            </head>
            <body>
                <h2>Records</h2>
                <xsl:apply-templates select="project/document"/>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="document">
        <article>
            <h3><xsl:value-of select="persons/person[@role='grantor']"/> to 
                <xsl:value-of select="persons/person[@role='grantee']"/></h3>
            <xsl:apply-templates select="docText"/> <!-- docText contains text inside CDATA section -->
            <div class="clear"/>
        </article><hr />
    </xsl:template>

    <!-- all lines of text are parsed here and tagged with either <p> or  <div> and blank lines discarded-->
    <xsl:template match="docText">
        <xsl:for-each-group select="tokenize(., '\n')[normalize-space()]" group-adjacent="string(analyze-string(., '^\[(witness|signed|clerk|margin)\]')//*:match/*:group)">
            <xsl:choose>
                <xsl:when test="current-grouping-key() and current-group()[2]">
                    <div class="current-grouping-key()-outer">
                        <xsl:apply-templates select="current-group()" mode="wrap-div">
                            <xsl:with-param name="class" select="current-grouping-key()"/>
                        </xsl:apply-templates>
                    </div>
                </xsl:when>
                <xsl:when test="current-grouping-key()">
                    <xsl:apply-templates select="current-group()" mode="wrap-div">
                        <xsl:with-param name="class" select="current-grouping-key()"/>
                    </xsl:apply-templates>                    
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()" mode="wrap-p"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>

    </xsl:template>

    <xsl:template match=".[. instance of xs:string]" mode="wrap-div">
        <xsl:param name="class"/>
        <div class="$class">
            <xsl:value-of select="replace(., '^\[.*?\]', '')"/>
        </div>
    </xsl:template>

    <xsl:template match=".[. instance of xs:string]" mode="wrap-p">
        <p>
            <xsl:sequence select="mf:rep-quotes(.)"/>
        </p>
    </xsl:template>

    <xsl:function name="mf:rep-quotes">
        <xsl:param name="input" as="xs:string"/>
        <xsl:analyze-string select="$input" regex="''([a-zA-Z]1,4)">
            <xsl:matching-substring>
                <sup><xsl:value-of select="regex-group(1)"/></sup>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:function>

</xsl:stylesheet>

我得到的输出是

<!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Test Title</title><style>
                    div background-color: pink;
                    p background-color: ; clear: right; margin-bottom: 0;
                    .clerk, .signed float:right;
                    .margin::before content: "[margin note:] ";
                    .clear clear: right;
                </style></head>
   <body>
      <h2>Records</h2>
      <article>
         <h3>Jane Doe to 
            Bob Jones
         </h3>
         <p>[page 001] 1</p>
         <div class="margin"> Person1 to Person2</div>
         <p>This Indenture made this x<sup>th</sup> Day of y in the year z Between person1,     grantor, of place1 to person2, grantee,
            of place2 for 5 dollars ... the s<sup>d</sup> person1 to s<sup>d</sup> person2 ... signed under my hand.
         </p>
         <p>Witnesses present</p>
         <div class="signed"> Mrs. Jane Doe (seal)</div>
         <div class="witness-outer">
            <div class="witness"> Mr. Witness1</div>
            <div class="witness"> Ms. Witness1</div>
         </div>
         <p>Court office month x<sup>th</sup> year
         </p>
         <p>I do hereby certify that ... and is thereon truly admitted to Record</p>
         <div class="clerk"> John G. Reynolds DCCC</div>
         <div class="clear"></div>
      </article>
      <hr>
      <article>
         <h3>John Doe to 
            Bob Jones
         </h3>
         <p>[page 002] 2</p>
         <div class="margin"> Person3 to Person4</div>
         <p>This Indenture made this x<sup>th</sup> Day of y in the year z Between person1, grantor, of place1 to person2, grantee, of
            place2 for 5 dollars ... the s<sup>d</sup> person1 to s<sup>d</sup> person2 ... signed under my hand.
         </p>
         <p>Witnesses present</p>
         <div class="signed"> Mr. John Doe (seal)</div>
         <div class="witness-outer">
            <div class="witness"> Mr. Witness1</div>
            <div class="witness"> Ms. Witness1</div>
         </div>
         <p>[page 003] 3</p>
         <p>Court office month x<sup>th</sup> year
         </p>
         <p>I do hereby certify that ... and is thereon truly admitted to Record</p>
         <div class="clerk"> John G. Reynolds DCCC</div>
         <div class="clear"></div>
      </article>
      <hr>
   </body>
</html>

【讨论】:

Martin,感谢您花时间和精力提供完整的工作解决方案。今晚我将研究您的解决方案,并使用更完整的 .xml 文件版本对其进行测试,看看是否可以添加其他步骤。几天前我刚刚开始添加 XSLT3 组件,因此我不熟悉解决方案中可能特定于该版本的一些内容。具体来说,我需要研究.[. instance of xs:string] 代码的作用。我没想过使用group-adjacent 选项,这似乎是一个很好的解决方案。谢谢,迈克尔 使用 XSLT 3.0,您也可以匹配原子值,而不仅仅是节点。符号.[. instance of xs:string] 作为模式匹配字符串值,因此这是一个处理来自例如字符串的模板。由for-each-group 处理的xsl:apply-templates select="current-group()"。该语法称为谓词模式w3.org/TR/xslt-30/#doc-xslt30-patterns-PredicatePattern。它需要一些时间来适应这种方法,但由于将 XSLT 中的 XML 处理分解为模板,它也有助于将纯字符串处理分解为模板。 我已将您的解决方案应用到我的 .xml 文档中,并且得到了我需要的大部分结果。我将&lt;xsl:value-of select="replace(., '^\[.*?\]', '')"/&gt; 更改为&lt;xsl:sequence select="mf:rep-quotes(replace(., '^\[.*?\]', ''))"/&gt;,以便&lt;div&gt; 中的文本也收到了标记。我需要添加一些额外的条件语句来处理转换为&lt;div&gt; 的括号格式指令,以满足我真实文档的更复杂需求。在 group-adjacent 指令之后,您会评论 //*:match/*:group 发生的事情吗?感谢您的帮助。 M. analyze-string 函数的结果返回一些包含 matchgroup 元素的 XML,并且使用的正则表达式 ^\[(witness|signed|clerk|margin)\] 包含方括号,但稍后仅包含方括号内的单词类需要我决定只使用括号内的单词,作为正则表达式中的第一个也是唯一的组,作为group-adjacent的分组键。使用例如*:match 只是由分析字符串函数返回的 match 元素的命名空间不可知选择。 好的,这有帮助。我以前没有见过或使用过不可知的命名空间引用。所以这就像我在原始模板中使用fn:match。我刚刚查看了https://www.w3.org/TR/xpath-functions-31/#func-analyze-string 的参考资料,发现返回了 3 种类型的元素:fn:match fn:non-match fn:group。我从你的帮助中学到了很多。非常感谢 - 迈克尔

以上是关于使用 XSLT 2.0/3.0 使用多个步骤将 CDATA 中的纯文本解析为 html。那里的一部分的主要内容,如果未能解决你的问题,请参考以下文章

在 pandas col 中将每第二行乘以 -1

使用 xslt 模板将多个图像添加到 docx 文件

使用 xslt 将 xml 复杂节点元素拆分为多个节点

使用 XSLT 将 XML 转换为多个 CSV

使用 XSLT 将 XML 转换为 CSV,用于在单个标记中以空格分隔的多个记录

XSLT 2 (Saxon):如何将多个文件读入内存