I need to add attribute at a given position. For example, my input is
<Transaction Type="a">
</Transaction>
I want to add attributes at position 1. I expect something like,
<Transaction price="1" count="1" Type="a">
</Transaction>
I invoke the following method. Here I append new attribute with already existing attribute. I remove already existing attribute and trying to add appended attribute at the end. I have attributes in insertedAttributes. xm.insertAttribute(insertedAttributes.toString()); doesnot seem to update the attributes. Hence, it results in
<Transaction>
</Transaction>
Code:
vtdXmlUtil.setComponents(transaction);
vtdXmlUtil.addAttributeAtPosition("/Transaction", "count=\"1\"", 1);
vtdXmlUtil.addAttributeAtPosition("/Transaction", "price=\"1\"", 1);
public void addAttributeAtPosition(String xPath, String attribute, int position) throws IOException, VTDException {
ap.selectXPath(xPath);
int i;
StringBuilder insertedAttributes = new StringBuilder();
while ((i = ap.evalXPath()) != -1) {
int count = vnav.getAttrCount();
count = count * 2;
int loc = 1;
for (int attr = 1; attr <= count; attr = attr + 2) {
if (loc == position) {
insertedAttributes = insertedAttributes.append(attribute);
}
insertedAttributes = insertedAttributes.append(" " + vnav.toString(i + attr) + "=\"" + vnav.toString(i + attr + 1) + "\"");
xm.removeAttribute(i + attr);
loc++;
}
}
vnav = xm.outputAndReparse();
ap.bind(vnav);
xm.bind(vnav);
xm.insertAttribute(insertedAttributes.toString());
vnav = xm.outputAndReparse();
ap.bind(vnav);
xm.bind(vnav);
}
I might be missing something. Is there any other way to add attributes at a given position as Im using naive method.
VTD-XML's output is not updated until you call XMLModifier's output or outputAndParse() method.
Please be aware that when you call various insert methods, you are doing nothing more than keeping records of what those changes are , whether it is a remove, add or update...
I read you code and could not see such invocation in any places...
============== New material here =============== I was able to adapt your code to my local environment and it seems to work for me... Below is the code that you will find very familiar..