[英]How to add Attribute as well as child element at same time for XML using XSLT
[英]How to move XML element and add a child element at the same time with XSLT?
我要在这里完成的工作是移动一个元素(包括它的子节点),然后在该元素中添加一个子节点,反之亦然。 看来我一次只能做一件事。 可以同时做两个吗?
这是我的输入XML
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<box1>
<cd1>
<title>Title 1</title>
<artist>Bob Dylan</artist>
<year>1985</year>
</cd1>
<cd2>
<title>Title 2</title>
<artist>Bonnie Tyler</artist>
<year>1988</year>
</cd2>
</box1>
<box2>
<cd3>
<title>Title 3</title>
<artist>Metallica</artist>
</cd3>
</box2>
</catalog>
想有这样的输出
<catalog>
<box1>
<cd1>
<title>Title 1</title>
<artist>Bob Dylan</artist>
<year>1985</year>
</cd1>
<cd2>
<title>Title 2</title>
<artist>Bonnie Tyler</artist>
<year>1988</year>
</cd2>
<cd3>
<title>Title 3</title>
<artist>Metallica</artist>
<year>1990</year>
</cd3>
</box1>
如您所见,元素cd3已移动,并且的子节点也已添加。
这就是我所做的一切,并且无论我按什么顺序放置代码,它都会移动元素。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<!-- add a child element -->
<xsl:template match="cd3">
<xsl:copy>
<xsl:apply-templates/>
<year>1990</year>
</xsl:copy>
</xsl:template>
<!-- move node -->
<xsl:template match="/catalog">
<xsl:copy>
<xsl:apply-templates />
<xsl:copy-of select="box2/cd3"/>
</xsl:copy>
</xsl:template>
<xsl:template match="box2"/>
</xsl:stylesheet>
将<xsl:copy-of select="box2/cd3"/>
更改为<xsl:apply-templates select="box2/cd3"/>
,并将<xsl:template match="/catalog">
更改为<xsl:template match="/catalog/box1">
。
我通过以下代码解决了它。 感谢您的帮助,让我开始了进一步的调查。
<xsl:template match="/catalog">
<xsl:copy>
<box1>
<xsl:apply-templates />
<xsl:apply-templates select="box2/cd3"/>
</box1>
</xsl:copy>
</xsl:template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.