| add element to xml [message #896539] |
Wed, 18 July 2012 14:55  |
anijdap ykus Messages: 4 Registered: July 2012 |
Junior Member |
|
|
Hello Pals!
Here is my initial xml file:
----------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<missions>
<mission number="1">
<name>first mission</name>
<score>1.0</score>
</mission>
<mission number="2">
<name>second mission</name>
<score>0.2</score>
</mission>
</missions>
----------------------------------------
I am trying to add a new element "mission" to my xml file.
here is a bit of my code:
--------------------------------------------------------------------
public class ModifyXMLFile {
public static void main(String[] args) {
try {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("c:\\file3.xml");
Document doc = (Document)builder.build(xmlFile);
Element missions = doc.getRootElement();
Element newMission= new Element("newMission");
missions.addContent(newMission);
// I want to add an attribute to newMission trying:
/* Attr number = doc.createAttribute("number");
number.setValue("3");
mission.setAttributeNode(number);
*/
--------------------------------------------------------------------
The above commented code does obviously not work. Any idea on how to get what I want?
I want the final xml to look like:
----------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<missions>
<mission number="1">
<name>first mission</name>
<score>1.0</score>
</mission>
<mission number="2">
<name>second mission</name>
<score>0.2</score>
</mission>
<newMission number="3">
<name>second mission</name>
<score>0.2</score>
</mission>
</missions>
-----------------------------------------------
what the functional part of my code gives me is:
-----------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<missions>
<mission number="1">
<name>first mission</name>
<score>1.0</score>
</mission>
<mission number="2">
<name>second mission</name>
<score>0.2</score>
</mission>
<newMission />
</missions>
-----------------------------------------------
I am not sure how to handle this.
Thanks in advance
|
|
|
|
Powered by
FUDForum. Page generated in 0.01493 seconds