如果子节点不存在于XML中使用xslt删除父节点
我想要使用xslt转换给定的XML。 需要注意的是,如果给定的子节点不存在,我将不得不删除父节点。 我做了一些模板匹配,但我卡住了。任何帮助,将不胜感激。如果子节点不存在于XML中使用xslt删除父节点
输入XML:
<Cars>
<Car>
<Brand>Nisan</Brand>
<Price>12</Price>
</Car>
<Car>
<Brand>Lawrence</Brand>
</Car>
<Car>
<Brand>Cinrace</Brand>
<Price>14</Price>
</Car>
</Cars>
我想删除不具有内它的价格因素的汽车。 所以预期输出是:
<Cars>
<Car>
<Brand>Nisan</Brand>
<Price>12</Price>
</Car>
<Car>
<Brand>Cinrace</Brand>
<Price>14</Price>
</Car>
</Cars>
我尝试使用这样的:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*" />
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Cars/Car[contains(Price)='false']"/>
</xsl:stylesheet>
我知道XSLT是完全错误的请指点。
UPDATE
更正其中一个工程:)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<!--Identity template to copy all content by default-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Car[not(Price)]"/>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<!--Identity template to copy all content by default-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Car[not(Price)]"/>
</xsl:stylesheet>
什么是你的身份模板中的car()?你不是指'node()'吗? – 2013-02-08 18:40:30
这从来没有奏效,它抛出了语法错误@ * | Car()'。'。 – hackmabrain 2013-02-08 18:53:54
身份模板似乎不对。请指教。 – hackmabrain 2013-02-08 18:54:14
超近。只要改变你的最后一个模板:
<xsl:template match="Car[not(Price)]"/>
而且,它不是不正确,但你可以结合你的2个xsl:output
元素:
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
_Identity模板似乎不对。请指教,它没有用._ – hackmabrain 2013-02-08 18:54:52
@hackmabrain咦?我没有使用身份模板。我只给了你最后一个模板的替代品。 – 2013-02-08 23:29:18
不同的解决方案是使用“的xsl:禁止复制'元素。
<?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" />
<xsl:template match="Cars">
<xsl:copy>
<xsl:copy-of select="Car[Price]" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
+1对于一个好的XSLT问题的所有3个元素。输入,输出,你试过的。 – 2013-02-08 18:42:06