| Author |
how to replace repeating value in XML
|
toledo alfresco
Greenhorn
Joined: Nov 09, 2012
Posts: 1
|
|
Hi all,
I have 2 repeating attributes, which I need to replace one with another. i.e.
<doc>
<data>
<old_year>2012</old_year>
<old_year>2013</old_year>
<old_year>2014</old_year>
</data>
<data>
<new_year>2010</new_year>
<new_year>2010</new_year>
<new_year>2011</new_year>
</data>
</doc>
The following can only replace the first value, and not others. Can someone help me understand why the other nodes gets empty value? Thanks.
public void someFunction () {
XPathExpression expr = xpath.compile("count(//doc/data/old_year)");
Integer yearCount = ((Double) expr.evaluate(doc, XPathConstants.NUMBER)).intValue();
System.out.println("Total anne values: " + yearCount.intValue());
for (int i=0; i < yearCount.intValue(); i++) {
xpathReplace(doc,"/doc/data/new_year[" + i + "]","/doc/data/old_year[" + i + "]");
}
}
private void xpathReplace(Document doc, String targetXpath, String sourceXpath) throws XPathExpressionException
{
Node sourceNode = null ;
Node targetNode = null ;
if(factory==null)
{
factory = XPathFactory.newInstance();
}
if(xpath==null)
{
xpath = factory.newXPath();
}
System.out.println("Sourc path: " + sourceXpath);
System.out.println("Target path: " + targetXpath);
sourceNode = (Node)xpath.evaluate(sourceXpath, doc,XPathConstants.NODE);
targetNode = (Node)xpath.evaluate(targetXpath, doc,XPathConstants.NODE);
if(sourceNode!=null && targetNode!=null )
{
targetNode.setTextContent(sourceNode.getTextContent());
}
}
|
 |
g tsuji
Ranch Hand
Joined: Jan 18, 2011
Posts: 357
|
|
The following can only replace the first value, and not others. Can someone help me understand why the other nodes gets empty value?
On the face of it, the code seems to intend to replace the new_year text by the correspondance, in position, old_year text value. It should run fine except that the last replacement wouldn't take place because the position() is 1-based rather than 0-based.
If you replace this
xpathReplace(doc,"/doc/data/new_year[" + i + "]","/doc/data/old_year[" + i + "]");
by this
the replacement will be complete.
But is that the problem or what you desire to happen?
|
 |
 |
|
|
subject: how to replace repeating value in XML
|
|
|