I have a jtree and need to save each child level element save as xml, I tried to using below code to implement it, but it gives errors for converting numeric data of the xml document,
Error message :
Exception in thread "AWT-EventQueue-0" org.jdom2.IllegalNameException: The name "1001" is not legal for JDOM/XML elements: XML name '1001' cannot begin with the character "1".
at org.jdom2.Element.setName(Element.java:227)
at org.jdom2.Element.<init>(Element.java:161)
at org.jdom2.Element.<init>(Element.java:173)
error pointed to, Element el = new Element(node.toString());
what may be the cause to the error?
// Save the XML file which has been modified.
private void saveMsg(TreeModel model) {
FileFilter filter = new FileNameExtensionFilter("xml files (*.xml)","xml");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setCurrentDirectory(new File(""));
fileChooser.setDialogTitle("Save XML file");
if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION){
//File file = fileChooser.getSelectedFile();
TreeModel tModel = xmlTree.getModel();
int childCount = tModel.getChildCount(tModel.getRoot());
logger.info("Messages to be sent : " + childCount);
for(int i=0; i<childCount; i++){
// go through each xml messages.
jtree2Xml(tModel.getChild(tModel.getRoot(), i));
}
}
} // End of Save XML file.
private void jtree2Xml(Object node) {
Document doc = new Document();
Element root = createTree(doc, xmlTree.getModel(), node);
doc.addContent(root);
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
try {
out.output(doc, System.out);
out.output(doc, new FileWriter(file));
System.out.println("Saved the xml file...");
} catch (IOException e) {
e.printStackTrace();
logger.error("Xml file saving error : ");
}
} // End of the method.
// Read through the document's elements.
private static Element createTree(Document doc, TreeModel model, Object node) {
**Element el = new Element(node.toString());**
for (int i = 0; i < model.getChildCount(node); i++) {
Object child = model.getChild(node, i);
el.addContent(createTree(doc, model, child));
} // End of the while loop.
return el;
}