[英]copy one complete element to a new XML when match the value of an attribute, and changing the value of another attribute inside, using XSLT
[英]XSLT copy element to another according to attribute value
我需要根據同一元素中另一個節點中的屬性復制一個節點。 示例輸入 XML 如下:
<?xml version="1.0"?>
<Company>
<Department id="Marketing">
<depName>Marketing</depName>
<position>Marketer</position>
</Department>
<Employee id="e1" level="l1">
<First>John</First>
<Dep code="Marketing"></Dep>
</Employee>
<Employee id="e2" level="l1">
<First>Jane</First>
<Dep code="Marketing"></Dep>
</Employee>
<Boss id="e3" level="l2">
<First>Ben</First>
<Dep code="Marketing"></Dep>
</Boss>
</Company>
output XML 應如下所示:
<?xml version="1.0"?>
<Company>
<Department id="Marketing">
<depName>Marketing</depName>
<position>Marketer</position>
</Department>
<Employee id="e1" level="l1">
<First>John</First>
<Dep code="Marketing"></Dep>
<position>Marketer</position>
</Employee>
<Employee id="e2" level="l1">
<First>Jane</First>
<Dep code="Marketing"></Dep>
<position>Marketer</position>
</Employee>
<Boss id="e3" level="l2">
<First>Ben</First>
<Dep code="Marketing"></Dep>
</Boss>
</Company>
當然可以有更多的員工和部門。 我需要將 position 元素從 Department 復制到該部門的每個員工(例如,對於 Marketing 有<Dep code="Marketing">
),而不是 Bosses 。 可以使用其id
屬性或depName
元素檢查部門,它們應該相同。
我是 XSLT 的新手,所以只需了解如何使用 select 元素,但不知道如何使用 go 從這里開始(復制到正確的位置):
<xsl:template match="Department">
<xsl:copy>
<xsl:copy-of select="position"/>
</xsl:copy>
</xsl:template>
編輯:為員工添加了屬性,他們需要保留在 output
聲明一個密鑰
<xsl:key name="dep" match="Department" use="@id"/>
然后為Employee
編寫模板
<xsl:template match="Employee">
<xsl:copy>
<xsl:copy-of select="@*, node(), key('dep', Dep/@code)/position"/>
</xsl:copy>
</xsl:template>
逗號運算,
適用於 XSLT 2 或 3 個處理器,對於 XSLT 1 處理器使用兩個單獨的
<xsl:copy-of select="@* | node()"/>
<xsl:copy-of select="key('dep', Dep/@code)/position"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.