使用 xslt 在输出 xml 中插入元素
我有以下 xml 文档:
<config>
<property name="prop1">val 1</property>
<property name="prop2">val 2</property>
</config>
我需要检查名称为“prop3”、“prop4”、“prop5”的属性是否存在,如果不存在,我需要将它们添加到配置下并保留现有元素。具有这些属性的元素可能存在,在这种情况下,我需要更改它们的值。有人可以帮忙吗?
i have the following xml document:
<config>
<property name="prop1">val 1</property>
<property name="prop2">val 2</property>
</config>
I need to check if properties with names "prop3", "prop4", "prop5" exist and if they don't, I need to add them under config keeping the existing elements. The elements with these properties may exist in which case, I need to change their values. Can someone help, please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个简短的转换:
当应用于提供的 XML 文档时:
产生完全想要的正确结果:
解释:
身份规则/模板“按原样”复制每个节点。
任何具有
name
属性的property
元素的重写模板,该属性具有my: 的
元素,实际上会从文档中删除任何此类元素(因为模板的正文为空。name
属性之一的值: replacements/property与文档顶部元素匹配的覆盖模板会浅复制它,然后复制其属性并将模板应用到其所有后代节点(实际上复制除上面 2. 中的那些之外的所有节点)。最后,它复制所有替换元素是嵌入式的孩子
my:replacements
元素。当这些替换元素位于单独的 XML 文档中(而不是像现在仅为方便起见那样位于 XSLT 样式表中)时,新复制的替换元素中出现的命名空间节点将消失。
请注意:此解决方案的主要思想是在元素存在时替换元素或在元素不存在时添加元素 - 这与复制新元素(不检查是否存在)相同覆盖任何现有元素。
This short and simple transformation:
when applied on the provided XML document:
produces exactly the wanted, correct result:
Explanation:
The identity rule/template copies every node "as-is".
The overriding template for any
property
element withname
attribute having the value of one of thename
attributes of themy:replacements/property
elements, in effects deletes any such element from the document (because of the empty body of the template.The overriding template that matches the top element of the document shallow-copies it, then copies its attributes and applies templates to all of its descendent nodes (in effect copying all of them except those in 2. above. Finally, it copies all replacement elements that are children of the embedded
my:replacements
element.The namespace nodes that appear in the newly copied replacement elements will disappear when these replacement elements are in a separate XML document (not in the XSLT stylesheet as is now done solely for convenience).
Do note: The main idea of this solution is that replacing elements when they exist or adding elements when they don't exist -- this is just the same as (without checking for existence) copying the new elements overwriting any existing elements.
下面是此类功能的示例 xsl 样式表:
这段代码基本上填充了 xml,以确保它包含从 prop1 到 prop5 的所有值。
不是那么复杂 - 因为我不知道确切的目的 - 但也许它会帮助你,并且你可以根据你的需要概括它。
这样,输出将
针对以下任何输入:
Here is a sample xsl stylesheet for such a functionality:
This piece of code basically fills up the xml to make sure that it contains all the values from prop1 to prop5.
Not that sophisticated -since i don't know the exact purpose-, but maybe it will help you out, and you can generalize it for your needs.
This way the output will be
for any of the following inputs: