2016-11-04 70 views
0
<main> 
    <parent> 
     <parentId>parentId1</parentId> 
     <aParentField>aParentValue 
     </aParentField> 
    </parent> 
    <child> 
     <parentId>parentId1</parentId> 
     <aChildField>aChildValue 
     </aChildField> 
    </child> 
</main> 

我是新来的XML,并试图将合并和B使用的ID作为参数结合起来,这样的结果应该是这样的:结合XML,XPath或XQuery的

<main> 
    <parent> 
     <parentId>parentId1</parentId> 
     <aParentField>aParentValue 
     </aParentField> 
     <child> 
      <aChildField>aChildValue 
     </aChildField> 
     </child> 
    </parent> 
</main> 

能有什么被使用和如何?

+0

你需要生成XMLFile或您的结果对象应该是所需的格式? – Maddy

+0

生成的对象应该是所需的格式。@ Maddy –

回答

2

这个例子有点模棱两可。假设你的输入可以有多个parent节点,每个节点链接到多个child节点,我建议你使用key,以解决交叉引用:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 

<xsl:key name="child" match="child" use="parentId" /> 

<xsl:template match="/main"> 
    <xsl:copy> 
     <xsl:apply-templates select="parent"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="parent"> 
    <xsl:copy> 
     <xsl:copy-of select="*"/> 
     <xsl:apply-templates select="key('child', parentId)"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="child"> 
    <xsl:copy> 
     <xsl:copy-of select="*[not(self::parentId)]"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
+0

如果我们再有一个孩子说child2的内容​​相同,该怎么办? @ michael.hor257k –

+0

@Tarun尝试一下,看看。 –

+0

它的工作,但我有嵌套元素不同的问题https://stackoverflow.com/questions/40493838/combining-xml-using-xslt-1-0 –