Not able to select XML root node having an attribute using XmlTask

232 views Asked by At
I want to insert an element in the XML.
This is an XML file - named web.xml

<web-app>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

This is the ANT task I am using to insert an element in the web-app node.

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" classpath="C:/xmltask.jar"/>    
<xmltask source="C:\web.xml" dest="C:\web.xml>              
     <insert path="/web-app">
          <![CDATA[
            <hello_world id="3">hello world</hello_world>
          ]]>
     </insert>          
</xmltask>      

Ant task run inserts the hello_world node in the web-app.

The insert (actually root node selection) fails when the root has an attribute.
So the xmltask insert doesn't work when the XML is -

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee">
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

I tried to use insert like this, but no luck -
<insert path="/web-app/[@xmlns='http://xmlns.jcp.org/xml/ns/javaee']">

What is the way to select the root node? Why this is not working, an explanation would help.

1

There are 1 answers

4
Patrice M. On

This is most likely a problem for XmlTask/xpath when the Xml uses a declared namespace (xmlns= is not just an attribute). See this other answer: https://stackoverflow.com/a/35778167/366749 I suggest you try:

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" classpath="C:/xmltask.jar"/>    
<xmltask source="C:\web.xml" dest="C:\web.xml>              
     <insert path="*[local-name()='web-app']">
          <![CDATA[
            <hello_world id="3">hello world</hello_world>
          ]]>
     </insert>          
</xmltask>