我有两个输入文件: 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获取的。换句话说,我想将file1.xml中的source替换为file2.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中的所有源节点。
我想我需要根据位置或父id的trans-unit是相同的位置做出选择。我试过了
<xsl:value-of select="document('file2.xlf')//source/parent::trans-unit[@id= current()]" />但这给了我<source/>。
我会感谢你给我的任何建议。
我的样式表是XSLT 1,但如果需要的话,我可以使用XLST2.0(我使用的是氧气和Saxon的免费版本)。
发布于 2017-06-18 11:07:15
假设您想通过匹配父source的id来查找trans-unit值,您可以这样做:
<xsl:value-of select="document('file2.xml')/xliff/file/body/trans-unit[@id=current()/../@id]/source" />在XSLT2.0中,通过将键定义为:
<xsl:key name="src" match="source" use="../@id" />然后将其用作:
<xsl:value-of select="key('src', ../@id, document('file2.xml'))" />发布于 2017-06-18 11:07:22
变化
<xsl:template match="source">
<source>
<xsl:value-of select="document('file2.xlf')//source" />
</source>
</xsl:template>至
<xsl:template match="source">
<xsl:copy-of select="key('ref', ../@id, document('file2.xlf'))/source" />
</xsl:template>将<xsl:key name="ref" match="trans-unit" use="@id"/>添加到样式表中(并确保在oXygen中使用Saxon 9来支持XSLT2.0)。
https://stackoverflow.com/questions/44614173
复制相似问题