Insert XML element in xml document using Ant

2019-03-01 10:05发布

问题:

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>