[英]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.