【发布时间】:2014-11-14 04:52:05
【问题描述】:
我已对问题进行了编辑以使其清楚。 我想获取所有包含节节点和标题节点的节节点,保持嵌套级别。下面是我想要的输出结果:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<section id="intro" difficulty="easy">
<title>Introduction</title>
<section>
<title>Web Data and the Two Cultures</title>
</section>
</section>
<section id="syntax" difficulty="medium">
<title>A Syntax For Data</title>
<section>
<title>Base Types</title>
</section>
<section>
<title>Representing Relational Databases</title>
</section>
<section>
<title>Representing Object Databases</title>
</section>
</section>
</results>
而xml内容是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="book.xsl"?>
<book>
<title>Data on the Web</title>
<author>Serge Abiteboul</author>
<author>Peter Buneman</author>
<author>Dan Suciu</author>
<section id="intro" difficulty="easy">
<title>Introduction</title>
<p>Text ... </p>
<section>
<title>Web Data and the Two Cultures</title>
<p>Text ... </p>
<figure height="400" width="400">
<title>Traditional client/server architecture</title>
<image source="csarch.gif"/>
</figure>
<p>Text ... </p>
</section>
</section>
<section id="syntax" difficulty="medium">
<title>A Syntax For Data</title>
<p>Text ... </p>
<figure height="200" width="500">
<title>Graph representations of structures</title>
<image source="graphs.gif"/>
</figure>
<p>Text ... </p>
<section>
<title>Base Types</title>
<p>Text ... </p>
</section>
<section>
<title>Representing Relational Databases</title>
<p>Text ... </p>
<figure height="250" width="400">
<title>Examples of Relations</title>
<image source="relations.gif"/>
</figure>
</section>
<section>
<title>Representing Object Databases</title>
<p>Text ... </p>
</section>
</section>
</book>
这是我的解决方案,这是错误的:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/book">
<xsl:apply-templates select="section"/>
</xsl:template>
<xsl:template match="section">
<xsl:element name="section">
<xsl:for-each select="@*">
<xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute>
</xsl:for-each>
</xsl:element>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="section"/>
</xsl:template>
<xsl:template match="title">
<xsl:element name="title">
<xsl:for-each select="@*">
<xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute>
</xsl:for-each>
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
我正在考虑使用递归,但我没有找到如何在 XSLT 中做到这一点。 应该有其他方法。 提前致谢!
【问题讨论】:
-
You are using "pull" rather than "push" kind of programming in your XSLT 尝试使用更多
apply-templates而不是for-each -
您的 XSLT 代码完全没有意义。您是否从某个地方复制它只是为了表明您已经尝试过某些东西?您只需要identity transform template 和另一个将
results重命名为book的模板。 -
我确实写了这个。我从昨天开始一直在努力,我还在尝试。我上面的 XSLT 代码是为了打印 html 文档中的元素。但现在我知道我应该将方法属性设置为xsl:输出元素为“xml”。所以不会有像<这样的符号不再。但我仍然找不到保持缩进格式和嵌套层次结构的方法。 @michael.hor257k