如果在第一个 XML 中设置了属性,则 XSLT 从第二个 XML 复制元素 [英] XSLT copy elements from second XML if an attribute is set in the first XML
问题描述
我有以下输入 XML:
car.xml:
I have the following input XMLs:
car.xml:
<car ref-id="parts.xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<color>red</color>
<tire>michelin</tire>
<engines override="false">
<engine>
<model>Z</model>
</engine>
</engines>
<hifi>pioneer</hifi>
</car>
parts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<parts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<engines>
<engine>
<model>X</model>
</engine>
<engine>
<model>Y</model>
</engine>
</engines>
<tire>goodyear</tire>
<color>black</color>
<airbag>true</airbag>
</parts>
我想将parts.xml 与car.xml 合并,但只想复制parts.xml 中的那些节点(不管它们的值如何):
I'd like to merge parts.xml with car.xml, but want to copy only those nodes from parts.xml (regardless of their value) which:
- A,在 car.xml 中不存在
- B, 存在于 car xml 中,但元素的覆盖"属性设置为 false.
Michael-hor257k 提供了一个 解决方案到A,但我坚持实现B.
Michael-hor257k provided a solution to A, but I'm stuck implementing B.
然后 XSLT 看起来像这样:
Then XSLT looks like this:
<xsl:variable name="loc">
<xsl:value-of select="car/@ref-id" />
</xsl:variable>
<xsl:template match="/car">
<xsl:variable name="local-names">
<xsl:for-each select="*">
<name>
<xsl:value-of select="name()" />
</name>
<attr>
<xsl:value-of select="@override" />
</attr>
</xsl:for-each>
</xsl:variable>
<xsl:copy>
<xsl:copy-of select="*" />
<xsl:copy-of
select="document($loc)/parts/*[not(name()=exsl:node-set($local-names)/name)] or
exsl:node-set($local-names)/attr='false'"/>
</xsl:copy>
</xsl:template>
我尝试添加
<attr>
<xsl:value-of select="@override" />
</attr>
和 或 exsl:node-set($local-names)/attr='false'
到 XSLT 但没有成功.
and
or exsl:node-set($local-names)/attr='false'
to the XSLT but no success.
推荐答案
您可以将第 10 行更改为:
You could change line #10 from:
<xsl:for-each select="*">
到:
<xsl:for-each select="*[not(@override='false')]">
您没有发布预期的结果,所以我不确定它会符合您的喜好.如果您需要合并不同级别的节点,这可能比看起来要复杂得多.
You didn't post the expected result, so I am not sure it will be to your liking. This could prove much more complicated than it seems, if you need to merge nodes at different levels.
这篇关于如果在第一个 XML 中设置了属性,则 XSLT 从第二个 XML 复制元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!