【问题标题】:How can I join 2 XML in 1 XSL如何在 1 个 XSL 中加入 2 个 XML
【发布时间】:2016-08-15 19:09:42
【问题描述】:

我有两个需要加入的.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>

谁能帮我解决这个问题?任何例如或关键字我应该查找这个问题?

【问题讨论】:

  • 开始,使用document函数读取Gerne.xml,得到GerneCodeGerneName,看看GerneCode是否匹配Songs.xml中当前元素的GerneCode和在Songs.xml 中的当前元素下复制GerneCodeGerneName。您可以使用 XpathFactory 用于 xpath 表达式和 TransformerFactory ,请参阅:docs.oracle.com/javase/7/docs/api/javax/xml/transform/…) 用于在拥有 xsl 后转换您的 xml。
  • 你可以使用 XSLT 2.0 吗?

标签: java xml xslt


【解决方案1】:

假设您仅限于 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(没有 &lt;/ns2:gernes&gt; 结束标记)。


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

【讨论】:

  • 谢谢。此解决方案有效。对不起我的英语不好,我的词汇有问题。
  • @BeansVănQuý 如果您的问题得到解答,请通过接受答案关闭它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2016-08-30
相关资源
最近更新 更多