我在C#中有一个函数来获取XML数据并使用XSLT样式表对其进行排序,然后返回已排序的数据并将其放入XMLDocument对象中.XSLT将无错误地处理数据,但它不会正确返回所有数据.如您所见,CarerContent的属性缺失.
这是XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="MatchedSources">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort data-type="number" order="descending" select="OverallMatchValue"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
输入XML数据如下所示:
<?xml version="1.0"?>
<MatchedSources responseId="1" dataSourceType="Document">
<MatchedSource>
<SourceId>1001</SourceId>
<DifferentPerspectives>
<Carer>
<CarerContent id="1" title="text">content</CarerContent>
<CarerContent id="2" title="text">content</CarerContent>
</Carer>
</DifferentPerspectives>
<OverallMatchValue>45</OverallMatchValue>
</MatchedSource>
<MatchedSource>
<SourceId>1002</SourceId>
<DifferentPerspectives>
<Carer>
<CarerContent id="1" title="text">content</CarerContent>
<CarerContent id="2" title="text">content</CarerContent>
</Carer>
</DifferentPerspectives>
<OverallMatchValue>78</OverallMatchValue>
</MatchedSource>
</MatchedSources>
Run Code Online (Sandbox Code Playgroud)
结果输出XML:
<?xml version="1.0"?>
<MatchedSources responseId="1" dataSourceType="Document">
<MatchedSource>
<SourceId>1002</SourceId>
<DifferentPerspectives>
<Carer>
<CarerContent id="1" title="text">content</CarerContent>
<CarerContent id="2" title="text">content</CarerContent>
</Carer>
</DifferentPerspectives>
<OverallMatchValue>78</OverallMatchValue>
</MatchedSource>
<MatchedSource>
<SourceId>1001</SourceId>
<DifferentPerspectives>
<Carer>
<CarerContent>content</CarerContent>
<CarerContent>content</CarerContent>
</Carer>
</DifferentPerspectives>
<OverallMatchValue>45</OverallMatchValue>
</MatchedSource>
</MatchedSources>
Run Code Online (Sandbox Code Playgroud)
小智 6
是的,这是一个常见的容易犯的错误.该<xsl:copy>只复制元素本身,它等同于<xsl:element name="{name()}">.您需要明确地复制属性节点.
例如,只需通过以下方式切换默认模板:
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望某些属性具有某些特定行为,请使用完整的"匹配设计":
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="MatchedSources">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-template/>
<xsl:sort data-type="number" order="descending" select="OverallMatchValue"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1638 次 |
| 最近记录: |