0

我有一个 jtree,需要将每个子级元素另存为 xml,我尝试使用下面的代码来实现它,但是它在转换 xml 文档的数字数据时出错,

错误信息 :

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)

错误指出,Element el = new Element(node.toString());

错误的原因可能是什么?

// 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;
    }
4

1 回答 1

0

来自 JDOM 的信息非常清楚。元素名称不能以字符“1”开头。这来自 XML 规范http://www.w3.org/TR/2004/REC-xml11-20040204/#NT-NameStartChar

您应该为元素使用固定名称,并将 JTree 节点 toString 放在一个属性中。

 <jtreenode value="1001"/>

罗弗尔

于 2013-04-19T10:06:31.820 回答