gpt4 book ai didi

xml - 如何使用xslt2.0在xml文件中以相同顺序获取特定的xml元素值?

转载 作者:行者123 更新时间:2023-12-03 17:05:40 24 4
gpt4 key购买 nike

这是我的Xml文件。我想使用xslt将这个xml文件转换成另一个自定义的xml文件。

XML文件:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
<w:p>
<w:r>
<w:t>Text1-</w:t>
</w:r>
<w:smartTag>
<w:smartTag>
<w:smartTag>
<w:smartTag>
<w:r>
<w:t>Text2-</w:t>
</w:r>
</w:smartTag>
</w:smartTag>
<w:r>
<w:t>Text3-</w:t>
</w:r>
<w:smartTag>
<w:r>
<w:t>Text4-</w:t>
</w:r>
</w:smartTag>
<w:r>
<w:t>Text5-</w:t>
</w:r>
</w:smartTag>
</w:smartTag>
<w:r>
<w:t>Text6-</w:t>
</w:r>
</w:p>
</w:body>
</w:document>


而我的XSLT片段是:

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<xsl:output method="html" indent="yes"/>

<xsl:template match="*">

<Document>
<xsl:choose>
<xsl:apply-templates select="//w:p[w:r[w:t]]">
</xsl:apply-templates>
</xsl:choose>
</Document>
</xsl:template>


<xsl:template match="w:p">
<Paragraph>

<xsl:if test="(.//w:smartTag/w:r/w:t)">
<xsl:apply-templates select="//w:smartTag//w:r//w:t"/>
</xsl:if>
<xsl:apply-templates select="./w:r/w:t"/>
</Paragraph>
</xsl:template>


<xsl:template match="w:t">
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>


我当前的输出是:

<Document>
<Paragraph>
Text2-Text3-Text4-Text5-Text1-Text6-
</Paragraph>
</Document>


我的必需输出是:

<Document>
<Paragraph>
Text1-Text2-Text3-Text4-Text5-Text6-
</Paragraph>
</Document>


请引导我获取元素而不丢失它保留的顺序...

最佳答案

除非您有关于应处理的内容的额外规则,否则可以简单地通过具有匹配w:t元素的模板来完成此操作

<xsl:template match="w:r/w:t">
<xsl:value-of select="." />
</xsl:template>


您还需要匹配项来处理文档和段落。尝试以下XML

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
exclude-result-prefixes="w">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
<Document>
<xsl:apply-templates />
</Document>
</xsl:template>

<xsl:template match="w:p">
<Paragraph>
<xsl:apply-templates />
</Paragraph>
</xsl:template>

<xsl:template match="w:r/w:t">
<xsl:value-of select="." />
</xsl:template>

<!-- Ignore text for all other elements -->
<xsl:template match="text()"/>
</xsl:stylesheet>


当应用于示例XML时,输出以下内容

<Document>
<Paragraph>Text1-Text2-Text3-Text4-Text5-Text6-</Paragraph>
</Document>

关于xml - 如何使用xslt2.0在xml文件中以相同顺序获取特定的xml元素值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11137440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com