XSLT,XPath:如何通过引用子元素的属性来获取父元素的属性?

时间:2019-04-23 15:21:43

标签: xml xslt xpath xslt-2.0 xpath-2.0

我的问题非常复杂,我不知道如何解决一个句子问题。因此,我尝试解释一下:我正在使用连接器(您可以在下面的代码xml输入中看到)。作为源,我具有元素“ ownedBehavior”的属性(xmi:id),它是元素“ subgroup”的子级,并且该元素“ subgroup”在其他元素“ group / node”中具有引用,因此我需要获取该元素组的属性。

XML输入的示例:


<packagedElement>
    <group xmi:type="ActivityPartition" xmi:id="EAID_LIFELINE_1" name="Course manager">
        <node xmi:idref="EAID_SUBGROUP_1"/>
    </group>
    <subgroup xmi:type="LoopNode" xmi:id="EAID_SUBGROUP_1" name="Loop Node">
        <ownedBehavior xmi:type="Activity" xmi:id="EAID_ACTIVITY_1" name="for each course"/>
        <ownedBehavior xmi:type="Activity" xmi:id="EAID_ACTIVITY_2" name="getCourse"/>
        <containedEdge xmi:type="ControlFlow" xmi:id="EAID_CONNECTOR1" source="EAID_ACTIVITY_2" target="EAID_ACTIVITY_3"/>
    </subgroup>
    <group xmi:type="ActivityPartition" xmi:id="EAID_LIFELINE_2" name="Course">
        <node xmi:idref="EAID_ACTIVITY_3"/>
    </group>
    <packagedElement xmi:type="Activity" xmi:id="EAID_ACTIVITY_3" name="selectCourse"/>
</packagedElement>
...
<connectors>
    <connector xmi:idref="EAID_CONNECTOR1">
        <source xmi:idref="EAID_ACTIVITY_2"/>
        <target xmi:idref="EAID_ACTIVITY_3"/>
    </connector>
</connectors>
...

但是在输出中,我只希望连接器具有正确的来源,并以属性ID(EAID_LIFELINE_1或EAID_LIFELINE_2)为目标的某个元素“组”是什么。因此, xml输出应如下所示:

<connectors>
    <connector xmi:idref="EAID_CONNECTOR1">
        <source xmi:idref="EAID_LIFELINE_1"/>
        <target xmi:idref="EAID_LIFELINE_2"/>
    </connector>
</connectors>

我尝试使用键功能和此XSLT

<xsl:key name="grp" match="group" use="node/@xmi:idref" />
<xsl:key name="subact" match="subgroup/ownedBehavior[@xmi:type='Activity']" use="@xmi:id" />
...
<connector xmi:idref="EAID_CONNECTOR{position()}">
     <source xmi:idref="{key('grp',../(key('subact',@source))/@xmi:id)/@xmi:id}"/> <!--This is place where I don´t know how to write that code to get to group...-->
     <target xmi:idref="{key('grp', @target)/@xmi:id}"/>
</connector>

目标是正确的,它显示了我想要的内容(EAID_LIFELINE_2),但是对于源代码,我不知道如何编写该xpath来获取生命线。你能帮我吗?谢谢。

1 个答案:

答案 0 :(得分:2)

您只是缺少从ownedBehaviorsubgroup的一个级别以获得正确的xmi:id的机会。因此,将您的connector代码更改为

<connector xmi:idref="EAID_CONNECTOR{position()}">
     <source xmi:idref="{key('grp',key('subact', @source)/../@xmi:id)/@xmi:id}"/> 
     <target xmi:idref="{key('grp', @target)/@xmi:id}"/>
</connector>

输出为:

<connector xmlns:xmi="urn:abc" xmi:idref="EAID_CONNECTOR6">
    <source xmi:idref="EAID_LIFELINE_1"/>
    <target xmi:idref="EAID_LIFELINE_2"/>
</connector>