如何基于当前XML元素值从其他XML文件获取对应元素?
Alright, let's sort this out. You've already loaded the external other_XML.xml into your titleCodes variable—great start! Now you just need to match elements from your current XML to the <job> entries in that external file, right?
First, let's assume your current working XML has entries that hold a matching identifier (like the bkz attribute from the external <job> elements). For example:
<current-data> <position> <matching-bkz>B 01104-101</matching-bkz> <!-- Other elements specific to your current XML --> </position> </current-data>
Option 1: Store the matched job in a variable (cleaner for reuse)
If you want to reuse the matched job data multiple times, store it in a variable first. Here's how:
<!-- When your current context is a <position> node (or whatever holds your matching value) --> <xsl:variable name="current-match-value" select="matching-bkz"/> <!-- Grab the corresponding <job> from the external XML --> <xsl:variable name="target-job" select="$titleCodes/job[@bkz = $current-match-value]"/> <!-- Now you can pull data from the matched job safely --> <xsl:if test="$target-job"> <job-details> <job-id><xsl:value-of select="$target-job/@id"/></job-id> <job-name-nl><xsl:value-of select="$target-job/name/name_nl"/></job-name-nl> </job-details> </xsl:if>
Option 2: Direct inline matching (for quick one-off uses)
If you only need to pull one piece of data, you can skip the intermediate variable and write the XPath directly:
<xsl:template match="position"> <div class="position-item"> <h3><xsl:value-of select="$titleCodes/job[@bkz = current()/matching-bkz]/name/name_nl"/></h3> <p>Job ID: <xsl:value-of select="$titleCodes/job[@bkz = current()/matching-bkz]/@id"/></p> </div> </xsl:template>
Key Notes
- If you need to match on the
idattribute instead ofbkz, just swap@bkzwith@idin the XPath (e.g.,$titleCodes/job[@id = current()/job-id]) - Always include the
<xsl:if test="$target-job">check (or ensure your XPath only returns a result if a match exists) to avoid empty or broken output when no match is found - The
current()function is important in inline matches—it refers to the current node in your working XML, not the external one
内容的提问来源于stack exchange,提问作者Niby
相关产品推荐
相关产品推荐

