[英]inserting an element in an xml document using its xpath
这是问题所在,我有一个不完整的文档(docA),想在一些xpath字符串(在doc elementList中)定义的某个特定位置插入一些xml元素,以获得完整的文档(docB)。
因此,基本上,给定文档docA:
<document>
<information type="person">
<id>string</id>
<customer>
<customerID>abc</customerID>
<externalID>2</externalID>
<person>
<gender>M</gender>
<firstName>John</firstName>
<!-- here should be a middle name -->
<lastName>Doe</lastName>
<birthdate>2011-05-05</birthdate>
</person>
<!-- more elements... -->
</customer>
<!-- more elements... -->
</information >
</document>
和elementList:
<newElementSet>
<element>
<name>Middle Name</name>
<path>/document/information/customer/person/middleName</path>
<value>Fitzgerald</value>
</element>
<!-- some more element could go there -->
</newElementSet>
输出文档应为:
<document>
<information type="private">
<id>string</id>
<customer>
<customerID>abc</customerID>
<externalID>2</externalID>
<person>
<gender>M</gender>
<firstName>John</firstName>
<middleName>Fitzgerald</middleName>
<lastName>Doe</lastName>
<birthdate>2011-05-05</birthdate>
</person>
<!-- more elements... -->
</customer>
<!-- more elements... -->
</information >
</document>
有什么办法可以在xslt中完成吗? 我尝试使用Xquery,但似乎不可能(由于尚不支持Xquery更新,因此无法使用)。
编辑:我只是想精确地说,这只是问题的简化表示。 实际上,我们要添加更多元素,并且实际上将要从用户输入中获取值...
可以很容易地做到这一点,您只需将“ elementList”文档稍作更改-更改为以下XML文档 :
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="person/firstName">
<xsl:call-template name="identity"/>
<middleName>Fitzgerald</middleName>
</xsl:template>
</xsl:stylesheet>
然后将这种转换应用于提供的源XML文档 :
<document>
<information type="person">
<id>string</id>
<customer>
<customerID>abc</customerID>
<externalID>2</externalID>
<person>
<gender>M</gender>
<firstName>John</firstName>
<!-- here should be a middle name -->
<lastName>Doe</lastName>
<birthdate>2011-05-05</birthdate>
</person>
<!-- more elements... -->
</customer>
<!-- more elements... -->
</information >
</document>
并产生想要的正确结果 :
<document>
<information type="person">
<id>string</id>
<customer>
<customerID>abc</customerID>
<externalID>2</externalID>
<person>
<gender>M</gender>
<firstName>John</firstName>
<middleName>Fitzgerald</middleName><!-- here should be a middle name -->
<lastName>Doe</lastName>
<birthdate>2011-05-05</birthdate>
</person><!-- more elements... -->
</customer><!-- more elements... -->
</information>
</document>
讨论内容 :
与尝试实施任何类型的动态评估相比,此解决方案出奇的简单。
指定所需更改的XML文档是紧凑的。
该逻辑是直截了当的,不会像任何部分动态评估的实现那样令人费解。
不需要其他XSLT文档。
这是一个易于实现,理解和维护的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.