【发布时间】:2020-04-25 12:59:49
【问题描述】:
这类似于这个问题:XSLT-1.0: How to insert an element at a specific position with respect to the parent element,但那里的答案没有涵盖输入 XML 中缺少tag3 的情况
我想在 XML 文档中插入或更新一个标记(比如 tag4),如下所示,除了 tag1、tag2、tag3、tag4 和 tag5 都是可选的。
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="d" />
<tag5 value="e" />
</Begin>
即以下是示例输入和输出
输入:
<Begin>
</Begin>
输出:
<Begin>
<tag4 value="updated" />
</Begin>
输入:
<Begin>
<tag4 value="d" />
</Begin>
输出:
<Begin>
<tag4 value="updated" />
</Begin>
输入:
<Begin>
<tag1 value="a" />
<tag5 value="e" />
</Begin>
输出:
<Begin>
<tag1 value="a" />
<tag4 value="updated" />
<tag5 value="e" />
</Begin>
输入:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag5 value="e" />
</Begin>
输出:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag4 value="updated" />
<tag5 value="e" />
</Begin>
输入:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag5 value="e" />
</Begin>
输出:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="updated" />
<tag5 value="e" />
</Begin>
更新
我还希望能够保留 Begin 或 tag4 元素上可能已经存在的任何属性,例如:
输入:
<Begin someAttribute="someValue">
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="d" someOtherAttribute="someOtherValue" />
<tag5 value="e" />
</Begin>
输出:
<Begin someAttribute="someValue">
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="updated" someOtherAttribute="someOtherValue" />
<tag5 value="e" />
</Begin>
【问题讨论】:
-
你知道tag4元素上“可能已经存在”的属性的名称吗?
-
@michael.hor257k - 不,我不知道,它们可能会发生变化。所以我本质上想复制 tag4 元素,然后如果 tag4 元素存在则添加/更新我的“值”属性,如果不存在则创建它。
-
然后复制
tag4的所有属性并然后覆盖value属性,或者复制除value之外的所有属性。对于Begin元素,您可以简单地将其所有属性复制到其任何子元素之前(或连同其第一批子元素).. -
@michael.hor257k - 是的,这基本上就是我期望做的。 Michael Kay 已经给了我大部分我需要的东西,我相信我可以自己解决剩下的问题(除非他好心更新他的答案!)。完成此操作后,我将接受他的回答。
-
我的建议是在凯博士给出的答案之上的。我会给你同样的答案(希望减去第 1 行的错字)。这是我提到的第二个选项的实现示例:xsltfiddle.liberty-development.net/ehVZvvV