Get Element from another XML file, based on an ele

2019-08-27 21:22发布

I use the following XSLT code to extract a list of elements from another XML file:

<xsl:variable name="titleCodes" select="document('other_XML.xml')/list"/>

The other_XML.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="struktur_berufe.xsd">
    <job id="15339" bkz="B 01104-101">
        <type>t</type>
        <name>
            <name_nl>Job a</name_nl>
        </name>
    </job>
    <job>
        ...
    </job>
    ...
</list>

I now want to extract the id attribute of the job element, filtered by the name_nl element. The value by which I filter is from the XML file I am trying to transform, which looks like this:

<JobPost>
    <id>1</id>
    <title>
        Job a    <!-- value I filter by -->
    </title>
</JobPost>

Here's what I tried so far:

<TitleCode>
    <xsl:value-of select="$titleCodes/job[type='t']/name[name_nl=title]/ancestor::job/@id"/>
</TitleCode> 

However, the problem seems to be, that [name_nl=title] is empty, since it looks for thetitle element in the other_XML.xml, which it of course doesn't have.

I also tried using a variable like this:

<TitleCode>
    <xsl:variable select="title" name="ab"/>
    <xsl:value-of select="$titleCodes/job[type='t']/name[name_nl=$ab]/ancestor::job/@id"/>
</TitleCode> 

But that still return ''.

So is there any way to solve this problem?

2条回答
姐就是有狂的资本
2楼-- · 2019-08-27 21:49

Assuming you are in a template matching JobPost, the expression you want is this....

<xsl:value-of select="$titleCodes/job[type='t']/name[name_nl = current()/title]/ancestor::job/@id"/>

So current()/title selects the title element for the current JobPost node, not the name node in the expression.

If this doesn't work, it is probably because you have whitespace in the title node in your XML, so try this...

 <xsl:value-of select="$titleCodes/job[type='t']/name[name_nl = normalize-space(current()/title)]/ancestor::job/@id"/>

It is probably the white space causing issues with your second attempt with the variable too.

Note that you could also write the expression like this, to remove the use of ancestor in the expression

<xsl:value-of select="$titleCodes/job[type='t'][name/name_nl = normalize-space(current()/title)]/@id" />
查看更多
太酷不给撩
3楼-- · 2019-08-27 21:55

As you want to read the @id within <job>, it should be enough to put all your filters in one predicate:

job[type='t' and name/name_nl=$ab]/@id

This way there's no need to navigate.

查看更多
登录 后发表回答