You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用XPath拆分提取XML中flight-number节点的分段字符串并分别返回结果?

Split Flight Number Text into Separate Elements Using XPath

The key thing to know here is that XPath 1.0 can't handle string splitting or node creation—you'll need to use XPath 2.0 or later (or pair it with XSLT/XQuery, which are standard tools for XML transformations). Here's how to get your desired result:

XPath 2.0+ Solution

You can use the tokenize() function to split the text, then construct new flight-number elements for each segment. Here's the query:

/airline/flight-number ! (
  tokenize(., '–') ! element flight-number {
    attribute flight_id { replace(../@flight_id, '-0102$', concat('-010', position())) },
    text()
  }
)

Let's break this down:

  • tokenize(., '–'): Splits the text content of the original flight-number using the en dash (–) as the separator, giving you the strings "01" and "02".
  • element flight-number { ... }: Creates a new flight-number element for each split string.
  • attribute flight_id { ... }: Adjusts the flight_id attribute to match your example—we replace the trailing -0102 with -0101 for the first segment and -0102 for the second using position() to track which part we're on.
  • text(): Inserts the split segment as the text content of the new element.

Alternative: XSLT (Using XPath Under the Hood)

If you're working in an environment that supports XSLT (like most XML editors or processing tools), this might be more readable. Here's a minimal stylesheet that does the transformation:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/airline">
    <airline>
      <!-- Split the flight number text into segments -->
      <xsl:for-each select="flight-number/tokenize(text(), '–')">
        <flight-number>
          <!-- Adjust the flight_id attribute -->
          <xsl:attribute name="flight_id">
            <xsl:value-of select="replace(../@flight_id, '-0102$', concat('-010', position()))"/>
          </xsl:attribute>
          <!-- Insert the split segment as text -->
          <xsl:value-of select="."/>
        </flight-number>
      </xsl:for-each>
    </airline>
  </xsl:template>
</xsl:stylesheet>

Important Notes:

  • Ensure you're using an XPath 2.0+ compliant processor (e.g., Saxon, modern libxml2 builds).
  • Double-check the delimiter: your XML uses an en dash (–), not a regular hyphen (-), so make sure the tokenize() function uses the correct character.
  • If your flight_id pattern differs from the example, tweak the replace() regex to match your actual structure.

Content of the question originates from Stack Exchange, asked by aye decoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:44:10