gpt4 book ai didi

xslt - 如何通过模板xslt从子节点获取祖 parent 节点的属性?

转载 作者:行者123 更新时间:2023-12-02 22:20:15 25 4
gpt4 key购买 nike

XML:

<Grandparent>
<Parent>
<Children id ="1">
<Info>
<Name>
<label name ="chname" />
</Name>
</Info>
</Children>
<Children name ="2">
<Info>
<Name>
<label name="chname" />
</Name>
</Info>
</Children>
<Children id ="3">
<Info>
<Name>
<label name="chname" />
</Name>
</Info>
</Children>
</Parent>
</Grandparent>

XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="label">
<label id="../../../preceding-sibling::Children/@id">
<xsl:apply-templates select="@*|node()"/>
</label>
</xsl:template>

</xsl:stylesheet>

预期输出:

<Grandparent>
<Parent>
<Children id ="1">
<Info>
<Name>
<label id="1" name ="chname" />
</Name>
</Info>
</Children>
<Children name ="2">
<Info>
<Name>
<label id="2" name="chname" />
</Name>
</Info>
</Children>
<Children id ="3">
<Info>
<Name>
<label id="3" name="chname" />
</Name>
</Info>
</Children>
</Parent>
</Grandparent>

我通过模板将属性 id 添加到“label”标签。如何从子节点获取属性“id”?这是我的代码

<label id="../../../preceding-sibling::Children/@id"> 

它不起作用。我在这里遗漏了什么吗?

提前致谢:)

最佳答案

如果你想把一个Xpath表达式的结果作为一个属性,你需要使用属性值模板,所以你应该这样写

<label id="{../../../preceding-sibling::Children/@id}"> 

花括号表示它是一个要计算的表达式,而不是一个要按字面意义输出的字符串。

但是,我认为在这种情况下表达是错误的。你实际上应该这样做:

<label id="{../../../@id}">

这是完整的 XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*" />

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="label">
<label id="{../../../@id}">
<xsl:apply-templates select="@*|node()"/>
</label>
</xsl:template>

</xsl:stylesheet>

当应用于您的 XML 时,输出如下

<Grandparent>
<Parent>
<Children id="1">
<Info>
<Name>
<label id="1" name="chname"/>
</Name>
</Info>
</Children>
<Children name="2">
<Info>
<Name>
<label id="" name="chname"/>
</Name>
</Info>
</Children>
<Children id="3">
<Info>
<Name>
<label id="3" name="chname"/>
</Name>
</Info>
</Children>
</Parent>
</Grandparent>

关于xslt - 如何通过模板xslt从子节点获取祖 parent 节点的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13814841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com