【发布时间】:2021-03-26 19:52:20
【问题描述】:
什么 XSLT 会复制我的 XML 文档,通过更改一个属性值并删除另一个属性来修改特定路径的元素,并克服我遇到的错误消息?
我的 XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8" />
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/document/body/table/cell[@a2='delete me'][@a3='change me']" >
<!-- Not trying to change @a3 yet, just delete @a2. -->
<xsl:copy-of select="@*[name(.)!='a2']|node()" />
</xsl:template>
</xsl:stylesheet>
我的输入 XML 文档(从真实的 LibreOffice 文档示例简化):
<?xml version="1.0" encoding="UTF-8"?>
<document>
<body>
<otherstuff/>
<table>
<cell id="1" a1="keep me" a2="delete me" a3="change me">
cell contents #1
</cell>
<cell id="2" a1="keep me too">
cell contents #2
</cell>
<not_cell id="3" a1="keep me" a2="delete me" a3="change me">
not_cell contents #3
</not_cell>
</table>
<otherstuff/>
</body>
</document>
我要更改的是具有a2="delete me" 和a3="change me" 属性的cell 元素应该更改。我想删除属性a2,并将a3 的值更改为a3="changed"。 cell 元素的所有其余部分均未更改。 XML 文档的所有其他部分均未更改。
预期的输出文档:与输入相同,除了<cell id='1' …/>:
<cell id="1" a1="keep me" a3="changed">
注意<not_cell id="3" a2="delete me" …/> 没有被触及,因为它不是cell 元素。
当我将这个 XSLT 应用到这个文档时,我得到了什么:
% xsltproc Error-Cannot-add-an-attribute-node.xslt Doc.xml
runtime error: file Error-Cannot-add-an-attribute-node.xslt line 49 element copy-of
Cannot add an attribute node to a non-element node.
这似乎是说copy-of 表达式正在尝试将属性应用于属性或元素文本。我不能很好地跟踪 XSLT 的执行,以了解它到底哪里出错了。你能解释一下吗?
进行这种转换的正确 XSLT 模式(最好是 XSLT-1.0)是什么?
(可能是答案,XSLT: How to change an attribute value during xsl:copy?,将引导我找到正确的 XSLT 模式,但我看不出来。而且,它没有说明为什么我正在尝试的 XSLT 会导致该错误消息。)
【问题讨论】: