Insert XML element in xml document using Ant

醉酒当歌 提交于 2019-12-20 04:35:14

问题


I want to insert one xml element in xml document :-

Input XML:-

    <cus:try xmlns:cus="http://www.abc.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xt="http://www.efg.com">
     <cus:trying>
  <cus:query>
  <xt:resourceTypes>abc</xt:resourceTypes>
  <xt:envValueTypes>def</xt:envValueTypes>
     </cus:query>
 </cus:trying>
    </cus:try>

Output XML:-

 <cus:try xmlns:cus="http://www.abc.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xt="http://www.efg.com">
     <cus:trying>
  <cus:query>
  <xt:resourceTypes>abc</xt:resourceTypes>
  <xt:resourceTypes>bcd</xt:resourceTypes>
  <xt:envValueTypes>def</xt:envValueTypes>
     </cus:query>
 </cus:trying>
    </cus:try>

That means i'm trying to insert one more with namespaces. I need to insert exactly like this..

I'm trying below

   <xmltask source="abc.xml" dest="abc.xml">
<insert path="//*[local-name()='resourceTypes']"> <![CDATA[
        <xa:resourceTypes id="3"/>
        ]]>
    </insert>
    </xmltask>

However, it is failing.


回答1:


To get <insert> to work, explicitly refer to the namespace in the element. Also <insert>, by default, puts new elements under existing ones. The code below changes the default to after.

<xmltask source="abc.xml" dest="abc.xml">
    <insert path="//*[local-name()='resourceTypes']" position="after"> <![CDATA[
        <xt:resourceTypes xmlns:xt="http://www.efg.com">bcd</xt:resourceTypes>
    ]]>
    </insert>
</xmltask>

The resulting XML, based on the XML in the question:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<cus:try xmlns:cus="http://www.abc.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xt="http://www.efg.com">
  <cus:trying>
    <cus:query>
      <xt:resourceTypes>abc</xt:resourceTypes>
<xt:resourceTypes>bcd</xt:resourceTypes>
      <xt:envValueTypes>def</xt:envValueTypes>
    </cus:query>
  </cus:trying>
</cus:try>


来源:https://stackoverflow.com/questions/22514657/insert-xml-element-in-xml-document-using-ant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!