2016-11-04 28 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 –