我希望有人可以帮我将XML节点加入一个html输出元素!
我有这样的XML:
<book>
<section type="chapter">
<p type="chapterNumber">Chapter 1</p>
<p type="chapterTitle">This is the very first chapter of this book</p>
<p type="normaltext">1 Lorem ipsum dolor sit amet</p>
</section>
<section type="chapter">
<p type="chapterNumber">Chapter 2</p>
<p type="chapterTitle">This is the second chapter of this book</p>
<p type="normaltext">2 Lorem ipsum dolor sit amet</p>
</section>
<section type="chapter">
<p type="chapterNumber">Chapter 3</p>
<p type="chapterTitle">This is the third chapter of this book</p>
<p type="normaltext">3 Lorem ipsum dolor sit amet</p>
</section>
</book>
我想将xml转换为此html(将p type =“chapterNumber”和p type =“chapterTitle”连接到本书中每个部分的单个h1标记中):
<html>
<head><title>My book</title></head>
<body>
<section class="chapter">
<h1>Chapter 1 - This is the very first chapter of this book</h1>
<p class="normaltext">Lorem ipsum dolor sit amet</p>
</section>
<section class="chapter">
<h1>Chapter 2 - This is the second chapter of this book</h1>
<p class="normaltext">Lorem ipsum dolor sit amet</p>
</section>
<section class="chapter">
<h1>Chapter 2 - This is the third chapter of this book</h1>
<p class="normaltext">Lorem ipsum dolor sit amet</p>
</section>
</body>
</html>
这是我现在拥有的xslt,其中chapterNumer转换为一个h1,chapterTitle转换为另一个h1元素:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:output indent="yes"/>
<xsl:template match="/">
<html>
<head><title>My book</title></head>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="book/section[@type="chapter"]">
<section>
<xsl:apply-templates/>
</section>
<xsl:template match="book/section[@type="chapter"]/p[@type="chapterNumber"]">
<h1>
<xsl:apply-templates/>
</h1>
</xsl:template>
<xsl:template match="book/section[@type="chapter"]/p[@type="chapterTitle"]">
<h1>
<xsl:apply-templates/>
</h1>
</xsl:template>
<xsl:template match="book/section[@type="chapter"]/p[@type="normal"]">
<p>
<xsl:apply-templates/>
</p>
</xsl:template>
</xsl:stylesheet>
答案 0 :(得分:0)
如果您直接处理p type="chapterNumber"
的以下兄弟,则可以调整代码
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<html>
<head><title>My book</title></head>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="book/section[@type='chapter']">
<section class="chapter">
<xsl:apply-templates/>
</section>
</xsl:template>
<xsl:template match="book/section[@type='chapter']/p[@type='chapterNumber']">
<h1>
<xsl:apply-templates/>
<xsl:text> - </xsl:text>
<xsl:apply-templates select="following-sibling::p[@type = 'chapterTitle']/node()"/>
</h1>
</xsl:template>
<xsl:template match="book/section[@type='chapter']/p[@type='chapterTitle']"/>
<xsl:template match="book/section[@type='chapter']/p[@type='normaltext']">
<p>
<xsl:apply-templates/>
</p>
</xsl:template>
</xsl:stylesheet>