使用 XSLT 关联相关项 [英] Correlating related items using XSLT
本文介绍了使用 XSLT 关联相关项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 xml 输入,
I have the following xml input,
<Adult>
<Parent>
<Id>1</Id>
<Name>Nick</Name>
<Age>32</Age>
</Parent>
<Parent>
<Id>2</Id>
<Name>Michael</Name>
<Age>35</Age>
</Parent>
<Information xmlns="http://ws.apache.org/ns/synapse" xmlns:ns="www.abc.com">
<Children xmlns="">
<Child>
<Name>Anne</Name>
<Gender>Female</Gender>
<ParentId>1</ParentId>
</Child>
<Child>
<Name>Will</Name>
<Gender>Male</Gender>
<ParentId>1</ParentId>
</Child>
<Child>
<Name>Carney</Name>
<Gender>Female</Gender>
<ParentId>2</ParentId>
</Child>
</Children>
</Information>
</Adult>
目前我有一个根元素下的所有孩子.但我需要将每个孩子与其关联的父母分组.例如,所有 parentId = 1 的子元素都应该位于 Id - 1 的父元素下.最后它应该如下所示.
Currently I have all the children under a root element. But I need to group each child with it's associated parent. For an example all the children with parentId = 1 should come under the parent element with Id - 1. Finally it should appear as follows.
<Adult>
<Parent>
<Id>1</Id>
<Name>Nick</Name>
<Age>32</Age>
<Children>
<Child>
<Name>Anne</Name>
<Gender>Female</Gender>
<ParentId>1</ParentId>
</Child>
<Child>
<Name>Will</Name>
<Gender>Male</Gender>
<PareinId>1</PareinId>
</Child>
</Children>
</Parent>
<Parent>
<Id>2</Id>
<Name>Michael</Name>
<Age>35</Age>
<Children>
<Child>
<Name>Carney</Name>
<Gender>Female</Gender>
<ParentId>2</ParentId>
</Child>
</Children>
</Parent>
</Adult>
有人可以建议我完成这项工作的方法吗?任何帮助将不胜感激.
Can someone suggest me a way to get this done. Any help would be appreciated.
推荐答案
XSLT 有一个内置的 关键解决交叉引用的机制:
XSLT has a built-in key mechanism to resolve cross-references:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:syn="http://ws.apache.org/ns/synapse"
exclude-result-prefixes="syn">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="child" match="Child" use="ParentId" />
<xsl:template match="@*|node()">
<xsl:copy copy-namespaces="no">
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Parent">
<xsl:copy>
<xsl:apply-templates/>
<Children>
<xsl:apply-templates select="key('child', Id)"/>
</Children>
</xsl:copy>
</xsl:template>
<xsl:template match="syn:Information"/>
</xsl:stylesheet>
这篇关于使用 XSLT 关联相关项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文