Finding a resource-ref XML Tag In Ant Script

137 views Asked by At

I would like to programmatically remove a chunk of XML using an ant script. I found the wonderful xmltask task, but for the life of me I can't find the resource-ref node that I want to delete.

Here's a subsection of what my XML doc looks like. It's from a web.xml file that uses the standard DTD:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="WebApp_ID"
     version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>Foo</display-name>

  <resource-ref>
    <description>Something Clever</description>
    <res-ref-name>jdbc/foo1</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

  <resource-ref>
    <description>Reports Database</description>
    <res-ref-name>jdbc/foo2</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

</web-app>

I'm trying to remove the second resource-ref chunk like this:

<project name="test" basedir="." default="fixxml">
<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"/>
  <target name="fixxml" description="er doy">
    <xmltask source="web.xml" dest="output.xml">
      <remove path="/web-app/resource-ref/description[text()='Reports Database']" />
    </xmltask>
  </target>
</project>

However, it doesn't work. I've also tried the following remove statements:

<remove path="/web-app/resource-ref[2]" />
....
<remove path="//description[text()[normalize-space(.)='Reports Database']]"" />    

None of them have working. Does anyone see what I may be doing wrong with my queries?

2

There are 2 answers

0
Tom Purl On BEST ANSWER

Patrice's answer seems to describe the the issue best. Xpath seems to be ignoring my namespace. I therefore tried to fiddle with the "query string" using this knowledge and various xpath helpers written in Java. After quite a bit of time I finally gave up on this path.

I ended up fixing this issue by doing the following:

  1. Writing a shell script that removes the XML chunk.
  2. Calling that script from my Ant file.

Please note that for me, this isn't option A or B - it's more like option M. But I just couldn't really afford to learn all of the warts of Xpath and how it's implemented in popular Java libraries.

5
Patrice M. On

The main issue is likely that your web.xml declares a name-space, but your xpath ignores it. Please see: https://stackoverflow.com/a/35778167/366749

The other issue is potentially that your xpath expression designates the 'description' element as the node to delete, not its parent.

Suggested edit (untested):

<remove path="path="/*[local-name()='web-app']/*[local-name()='resource-ref'][2]"/>