如何获取特定元素值

时间:2015-02-18 16:18:52

标签: xml xslt

我有以下XML:

< - 一个或多个这个 - >

<Supplement>
<ID>321
    <SupplementType>
        <Glass>31DK</Glass>
    </SupplementType>
</ID>
</Supplement>

当我使用当前元素的select-value时,它给出了32131DK(“ID”和“Glass”元素的值)

在我的输出中,我想获得仅在“ID”元素之后的数字值(321)

无法更改xml输入,因为它原样来自制造商。

我的XSLT:

<xsl:element name="ProfileSpecification">
    <xsl:for-each select="Supplement/ID">
        <xsl:value-of select="."/>
    </xsl:for-each> </element>

输出我得到:

<ProfileSpecification>32131DK</ProfileSpecification>

我想要的输出:

<ProfileSpecification>321</ProfileSpecification>

1 个答案:

答案 0 :(得分:3)

您的方法不起作用,因为

<xsl:value-of select="."/>

返回context元素的字符串值。字符串值是所有后代文本节点的串联,而不仅仅是直接子节点。

你不应该简单地匹配/(我猜你这样做)并且将所有代码都放在这个单一模板中。相反,为重要元素定义单独的模板匹配,并使用apply-templates在文档中移动。

如果没有正当理由,请勿使用for-eachxsl:element也是如此 - 如果元素名称是静态已知的,请不要使用它,而是使用文字结果元素

XML输入

假设格式正确(单个根元素)和代表性(多个Supplement元素,正如您在问题文本中所述)输入XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Supplement>
        <ID>321
        <SupplementType>
            <Glass>31DK</Glass>
        </SupplementType>
        </ID>
    </Supplement>
    <Supplement>
        <ID>425
        <SupplementType>
            <Glass>444d</Glass>
        </SupplementType>
        </ID>
    </Supplement>
</root>

XSLT样式表

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" />

    <xsl:template match="/root">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Supplement">
        <ProfileSpecification>
            <xsl:value-of select="normalize-space(ID/text()[1])"/>
        </ProfileSpecification>
    </xsl:template>

</xsl:transform>

XML输出

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <ProfileSpecification>321</ProfileSpecification>
    <ProfileSpecification>425</ProfileSpecification>
</root>