如果之前有人问我,我很抱歉,但我甚至不知道要搜索的条款。我是xml和xslt的初学者,我希望从xml文件创建html输出。我的问题看起来像这样:
我的xml文件中的文字是:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<p>This is some text. This is the last bit of text.</p>
<add>This is some other <hi>text</hi>.</add>
</body>
我想要的输出是
<p>This is some text. This is some other <hi>text</hi>. This is the last bit of text.<p>
我不能只标记
<?xml version="1.0" encoding="UTF-8"?>
<body>
<p><a>This is some text.</a> <b>This is the last bit of text.</b><p>
<c>This is some other <hi>text</hi>.</c>
</body>
我想要做的是为需要插入文本的位置放置一个标记。有点像这样:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<p>This is some text. <insert n="1"/> This is the last bit of text.<p>
<addition n="1">This is some other <hi>text</hi>.</addition>
</body>
添加的文本可以在文档中的任何位置,但我可以轻松地手动分配n。有关如何使用我的xslt样式表实现此目的的任何想法吗?
编辑:在某些情况下,其中的文本包含更多带有xsl中相应模板的标签。我尝试自己解决这个问题,但无法弄清楚如何在密钥中应用模板,有人能指出我的解决方案吗?
非常感谢!
玛丽
答案 0 :(得分:0)
让我稍微修改你的例子,因为我怀疑只要有<addition n="1">
,最终都会有<addition n="2">
。
鉴于以下示例输入:
<body>
<p>Four score and seven years ago our fathers brought forth, <insert n="1"/>a new nation, conceived in liberty, and dedicated to the proposition that “all men are created equal.”</p>
<p>Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. <insert n="2"/>We come to dedicate a portion of it, as a final resting place for those who died here, that the nation might live. This we may, in all propriety do.</p>
<addition n="1">upon this continent, </addition>
<addition n="2">We are met on a great battle field of that war. </addition>
</body>
以下样式表:
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="*"/>
<xsl:key name="add" match="addition" use="@n" />
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="insert">
<xsl:value-of select="key('add', @n)"/>
</xsl:template>
<xsl:template match="addition"/>
</xsl:stylesheet>
将返回:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<p>Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in liberty, and dedicated to the proposition that “all men are created equal.”</p>
<p>Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle field of that war. We come to dedicate a portion of it, as a final resting place for those who died here, that the nation might live. This we may, in all propriety do.</p>
</body>
鉴于您增加的要求,请更改:
<xsl:template match="insert">
<xsl:value-of select="key('add', @n)"/>
</xsl:template>
为:
<xsl:template match="insert">
<xsl:apply-templates select="key('add', @n)/node()"/>
</xsl:template>