Java XSLT转换以输出源中不存在的元素,如果存在则保持原样
基本上我有源XMLJava XSLT转换以输出源中不存在的元素,如果存在则保持原样,java,xslt,xml-parsing,saxon,Java,Xslt,Xml Parsing,Saxon,基本上我有源XML <RootElement attr=yes> <parentElement> <ChildElement1>some value in str</ChildElement1> <ChildElement2>some value in str</ChildElement2> <ChildComplexType1>
<RootElement attr=yes>
<parentElement>
<ChildElement1>some value in str</ChildElement1>
<ChildElement2>some value in str</ChildElement2>
<ChildComplexType1>
<grandChildElement1>some value in str</grandChildElement1>
</ChildComplexType1>
</parentElement>
</RootElement>
str中的一些值
str中的一些值
str中的一些值
我正在使用XSLT将其更改为其他XML。
使用结果XML的使用者期望如下
<RootElement attr=yes>
<parentElement>
<ChildElement1>some value in str</ChildElement1>
<ChildElement2>some value in str</ChildElement2>
<ChildComplexType1>
<grandChildElement1>some value in str</grandChildElement1>
<grandChildElement2>Default Value/ From Source XML</grandChildElement2>
</ChildComplexType1>
</parentElement>
</RootElement>
str中的一些值
str中的一些值
str中的一些值
默认值/来自源XML
问题是我正在使用下面的匹配规则,但它不起作用。
有人能提出一个更好的规则吗?
我相信这是一个基本问题,请道歉,因为我是XSLT新手
<xsl:template match="@*|node()" priority="1">
<xsl:copy copy-namespaces="no">
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="*:parentElement"
priority="2">
<xsl:element name="{name()}"
namespace="http://namespace"
inherit-namespaces="no">
<xsl:namespace name="ns5"
select="'namespace'" />
<xsl:apply-templates select="@*|node()" />
</xsl:element>
</xsl:template>
<xsl:template match="*:ChildComplexType1">
<xsl:if test="not(*:grandChildElement2)" priority="3">
<grandChildElement2>defaultValue</grandChildElement2>
</xsl:if>
<xsl:apply-templates />
</xsl:template>
默认值
我认为问题在于在标识模板上使用“优先级”属性
<xsl:template match="@*|node()" priority="1">
请注意,我也在ChildComplexType1
模板中添加了xsl:copy
,但您似乎在使用问题中未提到的名称空间,因此您可能需要将其改为xsl:element
注意,有关模板优先级的信息,请参阅。特别要注意的是,最高的默认优先级是0.5。您似乎正在使用标识模板 您可以在这里查看这个页面,它非常全面地描述了模板
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="@*|node()">
<xsl:copy copy-namespaces="no">
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="*:parentElement">
<xsl:element name="{name()}"
namespace="http://namespace"
inherit-namespaces="no">
<xsl:namespace name="ns5"
select="'namespace'" />
<xsl:apply-templates select="@*|node()" />
</xsl:element>
</xsl:template>
<xsl:template match="*:ChildComplexType1">
<xsl:copy>
<xsl:apply-templates />
<xsl:if test="not(*:grandChildElement2)">
<grandChildElement2>defaultValue</grandChildElement2>
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>