我有两个需要连接的 .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/