如何使用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 originalflight-numberusing the en dash (–) as the separator, giving you the strings "01" and "02".element flight-number { ... }: Creates a newflight-numberelement for each split string.attribute flight_id { ... }: Adjusts theflight_idattribute to match your example—we replace the trailing-0102with-0101for the first segment and-0102for the second usingposition()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 thetokenize()function uses the correct character. - If your
flight_idpattern differs from the example, tweak thereplace()regex to match your actual structure.
Content of the question originates from Stack Exchange, asked by aye decoder
相关产品推荐
相关产品推荐

