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

基于多ID的XPath完整XML提取需求:获取指定ID节点的父节点及祖先节点

Solution to Extract Specific Nodes with Ancestors via XPath

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 bookstore branch containing the book with title/@id="1":

    /bookstore/book[title/@id='1']/ancestor-or-self::*
    

    This selects the book element, its parent bookstore, and all child elements under that book (title and price).

  • For the photostore branch containing the photo with title/@id="3":

    /photostore/photo[title/@id='3']/ancestor-or-self::*
    

    This picks the photo element, its parent photostore, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:37:42