【发布时间】:2014-05-21 01:40:32
【问题描述】:
我是 XSLT 和 XPath 的新手,正在努力编写样式表来合并两个文件。
对于这个问题,我将使用我正在努力解决的概念的一个简单示例,而不是我的实际数据。假设我有两个包含单独但相关数据的 xml 文件。 authors.xml 和 books.xml。 authors.xml 包含作者的集合,以及一些关于他们的基本信息,而 books.xml 包含书籍的集合,以及关于他们的信息(包括作者,重要的是)。
我想要一个生成的 XML 文件,其中包含作者集合 - 但在每个作者元素中,还有一个属于该作者的书籍集合。
到目前为止,我所做的最好的事情就是在每个作者内部复制书籍列表,我觉得我什至可能对这个问题采取了一种完全奇怪/错误的方法。我才刚刚开始了解样式表是如何处理的。
示例 authors.xml:
<authors>
<author>
<name>Jane Doe</name>
<age>25</age>
</author>
<author>
<name>John Smith</name>
<age>53</age>
</author>
</authors>
示例 books.xml:
<books>
<book>
<title>Flying Kites</title>
<author>Jane Doe</author>
</book>
<book>
<title>XSLT For Dummies</title>
<author>John Smith</author>
</book>
<book>
<title>Running Fast</title>
<author>Jane Doe</author>
</book>
</books>
示例output.xml:
<authors>
<author>
<name>Jane Doe</name>
<age>25</age>
<books>
<book>
<title>Flying Kites</title>
</book>
<book>
<title>Running Fast</title>
</book>
</books>
</author>
<author>
<name>John Smith</name>
<age>53</age>
<books>
<book>
<title>XSLT For Dummies</title>
</book>
</books>
</author>
</authors>
我还会提供我的当前样式表,但我担心它可能走错了路:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output encoding="ISO-8859-1" indent="yes" method="xml"/>
<xsl:variable name="books" select="document('books.xml')"/>
<xsl:template match="/">
<authors>
<xsl:apply-templates select="/authors/author"/>
</authors>
</xsl:template>
<xsl:template match="author">
<author>
<name><xsl:value-of select="./name"/></name>
<age><xsl:value-of select="./age"/></age>
<books>
<xsl:apply-templates select="$books/books/book"/>
</books>
</author>
</xsl:template>
<xsl:template match="book">
<!-- How to only copy if correct author? -->
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
我花了几个小时四处寻找,但没有找到解决我的问题 - 尽管我的发现帮助我理解了 XSLT 和 XPath 如何更好地工作。
here 的问题很有帮助,但主要是关于将更新的数据“附加”到现有文件中。与我更相关的部分是更新日期,提供的答案实际上并没有这样做 - 并且自己无法做到。
我也在/r/learnprogramming 上提出了我的问题,但我得到的唯一答复基本上是“XSLT 太糟糕了。现在逃跑。”
我很少寻求帮助,但我已经为此困惑了一段时间,甚至不知道我应该采取什么方法。任何帮助或建议将不胜感激。
如果相关,我正在使用 Saxon 9 来处理 xslt。
【问题讨论】: