我有两个输入文件:file1.xml和file2.xml,其结构相同但内容不同(source
和target
节点)。使用另一个文件中相同节点的值替换节点值
file1.xml(简化版本)
<?xml version="1.0" encoding="UTF-8"?>
<xliff>
<file>
<body>
<trans-unit id="MDSD_0">
<source>Gestioni els seus favorits</source>
<target>Gestioni els seus favorits</target>
</trans-unit>
<trans-unit id="MDSD_1">
<source>Favorits</source>
<target>Favorits</target>
</trans-unit>
</body>
</file>
</xliff>
file2.xml(简化版本)
<?xml version="1.0" encoding="UTF-8"?>
<xliff>
<file>
<body>
<trans-unit id="MDSD_0">
<source>Manage your bookmarks</source>
<target>Manage your bookmarks</target>
</trans-unit>
<trans-unit id="MDSD_1">
<source>Bookmarks</source>
<target>Bookmarks</target>
</trans-unit>
</body>
</file>
</xliff>
我想借此从file1.xml所有内容以外的源节点,我想从file2.xml中获得。换句话说,我想用file2.xml中的source
替换file1.xml中的source
。
我很想用Perl或PHP来做,但我认为在XSLT中它会更有效率。但是,我有点卡住了。
我的样式表:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="source">
<source>
<xsl:value-of select="document('file2.xlf')//source" />
</source>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这将产生以下的输出:
<?xml version="1.0" encoding="UTF-8"?>
<xliff>
<file>
<body>
<trans-unit id="MDSD_0">
<source>Manage your bookmarks</source>
<target>Gestioni els seus favorits</target>
</trans-unit>
<trans-unit id="MDSD_1">
<source>Manage your bookmarks</source> <!-- this one is wrong -->
<target>Favorits</target>
</trans-unit>
</body>
</file>
</xliff>
正如你所看到的,它使用仅在file2.xml第一个源节点的内容替换所有源file1.xml中的节点。
我想我需要根据位置或父母trans-unit
的id
是否相同来做出我的选择。我已经尝试过
<xsl:value-of select="document('file2.xlf')//source/parent::trans-unit[@id= current()]" />
但是那给了我<source/>
。
我会很感激任何提示。我的样式表是XSLT版本1,但我想我可以在必要时使用XLST 2.0(我使用的是氧气和免费版本的Saxon)。
XSLT 1.0的第一个解决方案不起作用。它产生''。我还没有尝试过的第二种解决方案,但它看起来与Martin提供的解决方案一样,所以它应该可以工作。谢谢! – msoutopico
它适用于我 - 但后来我的文件被命名为'file2.xml'(正如您的问题所述),而不是您的示例代码中使用的'file2.xlf'。 –
你说得对,我的错。我选择你的答案是更完整(第1版和第2版的解决方案),并且是第一个发布的答案。谢谢。 – msoutopico