Click here to Skip to main content
15,899,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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>
</MainRoot>

I need a java code with vtd-xml parse to append a new RootElement tag with its SunElement tag
Here is my java code

Java
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

Java
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>
</MainRoot>
Posted
Updated 18-Nov-15 7:20am
v2
Comments
Member 12150206 18-Nov-15 11:38am    
Can someone help me out on this?
Richard MacCutchan 18-Nov-15 12:58pm    
What have you tried?
Where are you stuck?
Member 12150206 18-Nov-15 13:22pm    
I have updated question with the code which I have tried. Thanks @Richard

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900