我怎样才能得到具体的元素值

How can I get the specific element value

我有以下 XML:

<--一个或多个这个-->

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

当我使用当前元素的 select 值时,它会给我 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>

你的方法行不通,因为

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

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

您不应该简单地匹配 /(我猜您会)并将所有代码放入这个单一模板中。相反,为重要的元素定义单独的模板匹配,并使用 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>