通过Java中的XSLT进行XML碎化
我需要转换具有表单嵌套(分层)结构的大型XML文件
Flat XML Hierarchical XML (multiple blocks, some repetitive) Flat XML
变为扁平(“粉碎”)forms,每个重复嵌套块有1个块。
数据具有许多不同的标签和层次结构变体(特别是在分层XML之前和之后的碎片XML的标签数量),因此理想情况下不应该对标签和属性名称或层次级别做出假设。
只有4个级别的层次结构的顶级视图看起来像
... ... ... A B ... ... ...
然后会得到所需的输出
... ... ... A ... ... ... ... ... ... B ... ... ...
也就是说,如果在每个级别i
存在Li
不同的组件,则将产生总共Product(Li)
不同组件(仅上述2,因为唯一的区分因素是级别4,因此L1*L2*L3*L4 = 2
)。
从我所看到的,XSLT可能是要走的路,但任何其他解决方案(例如,StAX甚至JDOM)都可以。
使用虚构信息的更详细的例子将是
123 A Street 28 List of previous jobs in the US 3 01/10/2001 38 01/12/2004 6 01/06/2005 10 List of previous jobs in the UK 2 01/05/1999 25 01/07/2001 3 true 6
上面的数据应该被分解为5个块(即,每个不同的块一个),每个块都将使所有其他标签保持相同,并且只有一个
元素。 因此,考虑到上面示例中的5个不同的
块,转换后的(“碎片”)XML将是
123 A Street 28 List of previous jobs in the US 3 01/10/2001 38 true 6 123 A Street 28 List of previous jobs in the US 3 01/12/2004 6 true 6 123 A Street 28 List of previous jobs in the US 3 01/06/2005 10 true 6 123 A Street 28 List of previous jobs in the UK 3 01/05/1999 25 true 6 123 A Street 28 List of previous jobs in the UK 3 01/07/2001 3 true 6
给出以下XML:
123 A Street 28 List of previous jobs in the US 3 01/10/2001 38 01/12/2004 6 01/06/2005 10 List of previous jobs in the UK 2 01/05/1999 25 01/07/2001 3 true 6
以下XSLT:
给出以下输出:
请注意,我添加了一个Output根元素以确保文档格式正确。
这是你想要的吗?
您也可以使用xsl:copy来复制更高级别的元素,但我需要多考虑一下这个元素。 使用上面的xslt,您可以获得更多控制权,但您还必须重新定义元素…
这是一个按要求的通用解决方案 :
应用于提供的简化(和通用)XML文档时 :
... ... ... A B ... ... ...
产生了想要的正确结果 :
... ... A ... ... ... ... B ... ...
现在,如果我们改变这条线 :
至:
并将转换应用于Employee
XML文档 :
123 A Street 28 List of previous jobs in the US 3 01/10/2001 38 01/12/2004 6 01/06/2005 10 List of previous jobs in the UK 2 01/05/1999 25 01/07/2001 3 true 6
我们再次得到想要的,正确的结果 :
123 A Street 28 List of previous jobs in the US 3 01/10/2001 38 true 6 123 A Street 28 List of previous jobs in the US 3 01/12/2004 6 true 6 123 A Street 28 List of previous jobs in the US 3 01/06/2005 10 true 6 123 A Street 28 List of previous jobs in the UK 2 01/05/1999 25 true 6 123 A Street 28 List of previous jobs in the UK 2 01/07/2001 3 true 6
说明 :处理在命名模板( StructRepro
)中完成,并由名为pLeafNodes
的单个外部参数控制,该参数必须包含要在结果中再现“向上结构”的所有节点的节点集。