gpt4 book ai didi

xpath - XSLT : select all nodes that start with

转载 作者:行者123 更新时间:2023-12-03 16:00:40 26 4
gpt4 key购买 nike

我正在尝试执行 XSLT 转换,其中输入 XML 是任意的。唯一不变的是它将有一个名称以“first”开头的节点。我需要获取该节点的值,它是直接兄弟节点。但是,以下模板仅生成 XML 声明。

如果重要的话,这段代码是使用 Nokogiri XML 解析器在 Ruby 中编写的。但是,我认为这更像是一个 XSLT/XPath 问题,而不是一个 Ruby 问题,因此需要相应地标记。

输入 XML:

<?xml version="1.0"?>
<employees>
<employee>
<first_name>Winnie</first_name>
<last_name>the Pooh</last_name>
</employee>
<employee>
<first_name>Jamie</first_name>
<last_name>the Weeh</last_name>
</employee>
</employees>

所需的输出 XML:

<?xml version="1.0"?>
<people>
<person>
<first>Winnie</first>
<last>the Pooh</last>
</person>
<person>
<first>Jamie</first>
<last>the Weeh</last>
</person>
</people>

XSLT:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8" />
<xsl:template match="/">
<xsl:for-each select="node()[starts-with(name(), 'first')]">
<people>
<person>
<name>
<first><xsl:value-of select="." /></first>
<last><xsl:value-of select="following-sibling::*[1]" /></last>
</name>
</person>
</people>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

最佳答案

如果输入 XML 像您建议的那样随意,我看不出如何将 employees/employee 更改为 persons/person。但是,您可以使用

大致达到正确的效果
<xsl:template match="*">
<xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>

<xsl:template match="*[starts-with(name(), 'first')]">
<first><xsl:apply-templates/></first>
</xsl:template>

<xsl:template match="*[preceding-sibling::*[1][starts-with(name(), 'first')]]">
<last><xsl:apply-templates/></last>
</xsl:template>

关于xpath - XSLT : select all nodes that start with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042829/

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