Here is my current xml file,
<MainRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Root>
<RootElement name="rootelement1" date="21.Nov">
<SubElement id="32"/>
</RootElement>
<RootElement name="rootelement2" date="1.Dec">
<SubElement id="45"/>
</RootElement>
<RootElement name="rootelement3" date="18.Dec">
<SubElement id="12"/>
</RootElement>
</Root>
I need a java code with vtd-xml parse to append a new RootElement tag with its SunElement tag Here is my java code
public static void main(String[] args) {
VTDGen vtdGenerator;
VTDNav vtdNavigator;
XMLModifier xmlModifier;
AutoPilot autoPilot;
vtdGenerator = new VTDGen();
if (vtdGenerator.parseFile("test.xml", false)) {
vtdNavigator = vtdGenerator.getNav();
autoPilot = new AutoPilot(vtdNavigator);
autoPilot.bind(vtdNavigator);
autoPilot.selectElement("RootElement");
xmlModifier = new XMLModifier();
while (autoPilot.iterate()) {
// code to insert new RootElement tag with its subElment tag and
// their atributes
}
}
xmlModifier.output(new FileOutputStream("test.xml"));
}
I can insert single tag using this
xmlModifier.insertAfterElement("<RootElement name=\"rootelement4\" date=\"21.Dec\">\n\t\t<SubElement id=\"66\"/>\n</RootElement>");
but I want to insert multiple RootElement tags which is now allowed by this process. can anyone help me on this to append multiple tags to an xml. Is there any other approach to this. I don't want to use DOM parser, as the order of attributes are not guaranteed with DOM.
I need output like this,
<MainRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Root>
<RootElement name="rootelement1" date="21.Nov">
<SubElement id="32"/>
</RootElement>
<RootElement name="rootelement2" date="1.Dec">
<SubElement id="45"/>
</RootElement>
<RootElement name="rootelement3" date="18.Dec">
<SubElement id="12"/>
</RootElement>
<RootElement name="rootelement4" date="21.Dec">
<SubElement id="66"/>
</RootElement>
</Root>
Consider appending multiple RootElement to a single string, and then inserting that string into the existing XML as a single unit. If you use insertBeforeElement, Then toElement(VTDNav.PrevSibling) would move the cursor back... remember that XMLModifier doesn't honor document change instantly, therefore the underlying vtd and indexing full reflect the content and structure of the original document.