基于多ID的XPath完整XML提取需求:获取指定ID节点的父节点及祖先节点
Let’s break down how to get the exact XML structure you’re looking for using XPath (plus a little XSLT help for precise restructuring, since XPath alone can’t filter out irrelevant sibling nodes):
Step 1: Target the Relevant Branches with XPath
First, use XPath to identify the nodes you care about and their full ancestor chain:
For the
bookstorebranch containing the book withtitle/@id="1":/bookstore/book[title/@id='1']/ancestor-or-self::*This selects the
bookelement, its parentbookstore, and all child elements under that book (titleandprice).For the
photostorebranch containing the photo withtitle/@id="3":/photostore/photo[title/@id='3']/ancestor-or-self::*This picks the
photoelement, its parentphotostore, and the child elements under that photo.
Step 2: Restructure to Exclude Irrelevant Nodes
XPath can select the right nodes, but to strip out the unwanted book (the one with id="2"), you’ll need a simple XSLT template that uses those XPath queries to filter and copy only the content you want. Here’s the template:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <!-- Match root nodes that contain our target titles --> <xsl:template match="/bookstore | /photostore"> <xsl:copy> <!-- Only copy child elements linked to our target ids --> <xsl:apply-templates select="*[title/@id='1' or title/@id='3']"/> </xsl:copy> </xsl:template> <!-- Copy all other elements and their attributes/content --> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates/> </xsl:copy> </xsl:template> </xsl:stylesheet>
Step 3: Get Your Expected Output
When you apply this XSLT to your input XML, you’ll get exactly the structure you want:
<bookstore> <book> <title lang="en" id="1">Harry Potter</title> <price>29.99</price> </book> </bookstore> <photostore> <photo> <title lang="en" id="3">Learning XPATH</title> <price>1.00</price> </photo> </photostore>
Quick Note
XPath is perfect for selecting nodes, but XSLT adds the control needed to trim away irrelevant parts of the XML tree. This combination gives you the precise output you’re after.
内容的提问来源于stack exchange,提问作者GJF

