使用 xslt 操作 xml 文件中元素中的值

问题描述 投票:0回答:1

我希望能够删除或替换 xml 文件中元素值内不必要的文本,并且我想使用 XSLT 转换来做到这一点。

在此示例文件中,我想删除特定标签,如 br、前缀、后缀、项目符号列表,或将它们替换为 Value 元素值内的特定文本或简单字符。

会有很多Product元素。我不想更改此文件的结构,因此这应该类似于副本,但具有删除特定文本的逻辑。

我尝试使用模板和复制,但不知何故我无法将它们连接在一起。

如果你们中的任何人可以帮助我或给我应该遵循的提示,我将不胜感激。

<ProductInfo>
  <Products>
    <Product>
     <Name>xyz</Name>
     <Values>
        <Value><br/>test</Value> <-- remove <br/>
        <Value><preffix>test2</preffix></Value> <-- replace <preffix> and </preffix> with " ." (white space and dot)
        <Value><suffix/>test3</Value> <-- remove <suffix/>
        <Value><list/><bulletlist>test4</bulletlist></Value> <-- replace <bulletlist> with "<ul>, </bulletlist> with </ul>"
     </Values>
    </Product>
  <Product>
     <Name>xyz</Name>
     <Values>
        <Value><br/>test</Value> <-- remove <br/>
        <Value><preffix>test2</preffix></Value> <-- replace <preffix> and </preffix> with " ." (white space and dot)
        <Value><suffix/>test3</Value> <-- remove <suffix/>
        <Value><list/><bulletlist>test4</bulletlist></Value> <-- replace <bulletlist> with "<ul>, </bulletlist> with </ul>"
     </Values>
    </Product>
  </Products>
</ProductInfo>

输出文件应如下所示:

<ProductInfo>
  <Products>
    <Product>
     <Name>xyz</Name>
     <Values>
        <Value>test</Value>
        <Value> .test2 .</Value>
        <Value>test3</Value>
        <Value><ul>test4</ul></Value>
     </Values>
    </Product>
  <Product>
     <Name>xyz</Name>
     <Values>
        <Value>test</Value>
        <Value> .test2 .</Value>
        <Value>test3</Value>
        <Value><ul>test4</ul></Value>
     </Values>
    </Product>
  </Products>
</ProductInfo>
xml xslt xslt-1.0 xslt-2.0
1个回答
0
投票

要获得您显示的结果,您需要执行以下操作:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<!-- remove br, suffix, list -->
<xsl:template match="br | suffix | list"/>

<!-- replace prefix tags with text, keep contents -->
<xsl:template match="preffix">
    <xsl:text> .</xsl:text>
    <xsl:apply-templates/>
    <xsl:text> .</xsl:text>
</xsl:template>

<!-- rename bulletlist -->
<xsl:template match="bulletlist">
    <ul>
        <xsl:apply-templates/>
    </ul>
</xsl:template>

</xsl:stylesheet>

请注意,这假设

suffix
list
(当然还有
br
)都是空的。

© www.soinside.com 2019 - 2024. All rights reserved.