I am trying to take user input from a console and feed that into a XML file. Evrytime the user moves on to the next line I want to take the string they typed in and create a new element. Here is what I am trying to achieve:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
<header>
<Tempo Laya="2"/>
</header>
<Notes>
<n1 Bol="Text the user entered"/>
<n2 Bol="Text the user entered over the next iteration"/>
<n3 Bol="Text the user entered over the next iteration"/>
</Notes>
</note>
I thought the best way to do this would be to create these elements, however; I am not able to create unique element names through this. Here is my code so far:
//Create note element
Element notes = doc.createElement("Notes");
rootElement.appendChild(notes);
System.out.println("Input your notes matraa by maatra. To proceed to the next maatra press ENTER. \n To exit enter END");
do{
int noteCount = 1;
System.out.println("Maatra: ");
bol = scanner.nextLine();
}while(scanner.nextLine()!= "END");
Is there any way to create and append the elements using the loop above. If not how else could I do it?
First you have a bug when checking the "END"
string. You should use String.equals
instead of reference equality. Also calling nextLine()
twice reads two lines instead of one. Just check the first read line:
while(bol.equals("END"));
Second it would be much easier to use JAXB to perform this task. Whenever a new input is added by the user, you add a new object in memory, as opposed to manually handling the document tree. Once the "END"
is received, the contents are marshalled as a document.
You can read an introduction to JAXB in the Oracle tutorials.
If you still want to use standard DOM to do this, you would need to do something like:
Element noteElement = doc.createElement("note");
notes.appendChild(noteElement);
This means, as @Andreas commented below, the elements should ideally have the same name, not sequentially numbered (n1, n2, n3, ...). If numbering is really needed, you can add another attribute containing the id (using the method createAttribute
in Document
similar to createElement
).