java - 如何在 1 个 XSL 中加入 2 个 XML

标签 java xml xslt

我有两个需要连接的 .xml 文件

第一个文件是Song.xml,如下所示:

<Songs>
  <Song>
    <SongID>1</SongID>
    <SongName>We dont talk anymore</SongName>
    <Author>M-TP</Author>
    <UploadBy>admin</UploadBy>
    <GerneCode>1</GerneCode>
  </Song>
</Songs>

以及从架构生成的 Gerne.xml

<ns2:gernes xmlns="http://www.w3.org/2001/XMLSchema/playlist" xmlns:ns2="https://xml.netbeans.org/schema/genses">
    <ns2:gerne>
        <GerneCode>1</GerneCode>
        <GerneName>Pop</GerneName>        
        <Image>img-pop.jpg</Image>
    </ns2:gerne>
</ns2:gerne>

我想将这些 .xml 文件加入到 XSL 中,其中将为每首与 Gerne.xml 中的 GerneName 相匹配的歌曲添加 GerneName。

我想要得到的结果应该是这样的:

<Songs>
      <Song>
        <SongID>1</SongID>
        <SongName>We dont talk anymore</SongName>
        <Author>M-TP</Author>
        <UploadBy>admin</UploadBy>
        <GerneName>Pop</GerneName>
        <GerneCode>1</GerneCode>
      </Song>
</Songs>

有人可以帮我解决这个问题吗?对于这个问题我应该查找什么例如或关键字?

最佳答案

假设您仅限于 XSLT 1.0,您可以执行以下操作:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:pl="http://www.w3.org/2001/XMLSchema/playlist"
xmlns:ns2="https://xml.netbeans.org/schema/genses"
exclude-result-prefixes="pl ns2">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:variable name="lookup-path" select="'Gerne.xml'" />
<xsl:key name="genre" match="ns2:gerne" use="pl:GerneCode" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="GerneCode">
    <xsl:variable name="code" select="." />
    <!-- switch context to the other file -->
    <xsl:for-each select="document($lookup-path)">
        <GerneCode>
            <xsl:value-of select="key('genre', $code)/pl:GerneName" />
        </GerneCode>
    </xsl:for-each>
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

假设您告诉 XSLT 处理器处理 Song.xml文件,并将路径传递给 Gerne.xml文件作为参数。

请注意 Gerne.xml您发布的文档不是格式良好的 XML(没有 </ns2:gernes> 结束标记)。

<小时/>

顺便说一句,正确的术语是“流派”,而不是“gerne”或“gense”。

关于java - 如何在 1 个 XSL 中加入 2 个 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961434/

相关文章:

java - 我们可以在 Java 7 中同时使用 try with resources 和 multi-catch 吗?

java - 如何使用 Selenium 和 Java 填写 yahoo 登录页面中的用户名和密码字段

用于重新排序 XML 元素的 C API?

java - 修复XPath表达式中的绝对路径,以便它们可在另一个文档的上下文中使用

xml - 如何仅使用 XInclude 在 XML 上应用 XSLT

java - Maven 使用不同的依赖项创建相同的项目

xml - 使用 XSLT 根据 XML 中的文本拆分元素

xslt - 客户端XSLT

xml - 使用带有变量的 XSL include 语句

java - 最小化 setOnSeekBarChangeListener 样板