Following discussion w/ Scott and Jeff in alexandria-dev, I quickly wrote an XPath task.
I'm not sure this is 'exactly' how it should be done...
this looks like more a feature of the replace task, but I also wanted the
multiple replace feature without parsing n times the xml document.
Use at as follows:
<xpath file="input.xml" tofile="output.xml">
<apply select="/root/node/@attribute" value="newvalue"/>
<apply select="/root/node/child/@attribute" value="newvalue"/>
</xpath>
or simply:
<xpath file="input.xml" select="/root/node/@attribute" value="newvalue"/>
So here is the XPath task, with testcase and doc.
I used the package org.apache.tools.ant.taskdefs.optional.xpath
Feel free to change it to a more appropriate one (for instance if it is to
be used in cjan or alexandria).
Cheers,
--
St�phane Bailliez
Software Engineer, Paris - France
iMediation - http://www.imediation.com
Disclaimer: All the opinions expressed above are mine and not those from my
company.
TestXPath.java
Description: Binary data
XPath.java
Description: Binary data
XPath
by
- Stephane Bailliez ([EMAIL PROTECTED])
Requirements
This task requires Xalan 2.x and a JAXP compliant parser.
Description
Invokes the Xalan XPath API over an XML document and replace specified node values by new values.
Parameters
| Attribute | Description | Required |
| file | The XML file to which the Audit result should be written to. | Yes |
| tofile | The XML file resulting from the XPath modifications. | No (default is to modify the source file) |
| select | The XPath _expression_ that select nodes to process. | No. (Yes if select is set) |
| value | The value to replace | No. (Yes if select is set) |
Nested elements
apply
An XPath _expression_ to apply on the XML document.
| Attribute | Description | Required |
| select | The XPath _expression_ that select nodes to process. | Yes. |
| value | The value to replace | Yes. |
Note that XPath expressions will be evaluated in the order they are declared. The one declared as attributes of xpath being the first one (if declared).
Example
<xpath file="./xml/input.xml" tofile="./xml/output.xml">
<apply select="/root/nodea/@attr1" value="newvalue1"/>
<apply select="/root/nodeb/@attr5" value="newvalue5"/>
</xpath>
This invokes XPath and replace the value of the selected attributes by respectively newvalue1 and newvalue5, as indicated below:
| Before | After |
<root>
<nodea attr1="oldvalue1"/>
<nodea attr1="oldvalue1"/>
<nodeb attr5="oldvalue5"/>
</root>
|
<root>
<nodea attr1="newvalue1"/>
<nodea attr1="newvalue1"/>
<nodeb attr5="newvalue5"/>
</root>
|
