如何将元素(日期)作为属性添加到Level1元素
下面是 源xml
<level>
<date> 2019-jan-01<date>
<level1 name ="abc", age = 24>
<level2 val1 = "asd"> 2.34</level2>
</level1>
<level1 name ="abc", age = 24>
<level2 val1 = "asd"> 2.34</level2>
</level1>
</level>
目标XML
<level>
<level1 name ="abc", age = 24 , date = 2019-jan-01 >
<level2 val1 = "asd"> 2.34</level2>
</level1>
<level1 name ="abc", age = 24 , date = 2019-jan-01>
<level2 val1 = "asd"> 2.34</level2>
</level1>
</level>
答案 0 :(得分:2)
需要对源XML进行一点清理-删除逗号,添加引号等:
<level>
<date>2019-jan-01</date>
<level1 name="abc" age="24">
<level2 val1="asd">2.34</level2>
</level1>
<level1 name="abc" age="24">
<level2 val1="asd">2.34</level2>
</level1>
</level>
然后,此XSLT会将源转换为您的目标:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.1">
<!-- exclude the date element -->
<xsl:template match="date" />
<!-- copy the level1 element adding an attribute -->
<xsl:template match="level1">
<xsl:copy>
<xsl:attribute name="date">
<xsl:value-of select="../date/text()"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- keep everything the same unless explicit transformed by above -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
结果是:
<level>
<level1 date="2019-jan-01" name="abc" age="24">
<level2 val1="asd">2.34</level2>
</level1>
<level1 date="2019-jan-01" name="abc" age="24">
<level2 val1="asd">2.34</level2>
</level1>
</level>