XSLT 转换为 xml,按键分组 [英] XSLT transformation to xml, grouping by key
本文介绍了XSLT 转换为 xml,按键分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在编写 xsl 以将我的 xml 转换为 raport 版本时遇到问题.看起来像这样:
I have problem with write xsl to transform my xml to raport version. It looks like that:
<library>
<authors>
<author id="1001">John</author>
<author id="1002">Tom</author>
</authors>
<articles>
<article>
<authorId>1001</authorId>
<title>Article1</title>
</article>
<article>
<authorId>1002</authorId>
<title>Article2</title>
</article>
<article>
<authorId>1001</authorId>
<title>Article3</title>
</article>
</articles>
</library>
我想将其转换为:
<raport>
<authorArticles>
<author>John</author>
<articles>
<article>Article1</article>
<article>Article3</article>
</articles>
</authorArticles>
<authorArticles>
<author>Tom</author>
<articles>
<article>Article2</article>
</articles>
</authorArticles>
</raport>
我有想法为每个人使用,用于作者的 id 和文章的嵌套,但我不知道该怎么做.有人知道如何进行这种转换吗?
I have idea to use for each, on for ids in authors and neasted for articles, but I dont know how to do it. Anyone know how to make this transformation ?
推荐答案
这个 XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="node() | @*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="library">
<raport>
<xsl:apply-templates select="authors/author"/>
</raport>
</xsl:template>
<xsl:template match="author">
<authorArticles>
<xsl:call-template name="identity"/>
<articles>
<xsl:apply-templates select="../../articles/article[authorId = current()/@id]"/>
</articles>
</authorArticles>
</xsl:template>
<xsl:template match="article">
<xsl:call-template name="identity"/> <!-- In case of more characteristics -->
</xsl:template>
<xsl:template match="title">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="author/@id | authorId"/>
</xsl:stylesheet>
使用此 XML 输入:
With this XML input:
<library>
<authors>
<author id="1001">John</author>
<author id="1002">Tom</author>
</authors>
<articles>
<article>
<authorId>1001</authorId>
<title>Article1</title>
</article>
<article>
<authorId>1002</authorId>
<title>Article2</title>
</article>
<article>
<authorId>1001</authorId>
<title>Article3</title>
</article>
</articles>
</library>
提供所需的结果:
<raport>
<authorArticles>
<author>John</author>
<articles>
<article>Article1</article>
<article>Article3</article>
</articles>
</authorArticles>
<authorArticles>
<author>Tom</author>
<articles>
<article>Article2</article>
</articles>
</authorArticles>
</raport>
进一步的优化可能是使用键,但你的结构看起来还为时过早.
The further optimization might be using keys, but it looks premature with your structure.
这篇关于XSLT 转换为 xml,按键分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文