dom XML操作

一、创建XML文件

    public static void createXML(String filename) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder loader = factory.newDocumentBuilder();

            Document doc = loader.newDocument();

            Element root = doc.createElement("List");
            Element node = doc.createElement("Node");
            node.setAttribute("name", "jack");
            Element phone = doc.createElement("phone");
            Text phoneText = doc.createTextNode("12364");

            phone.appendChild(phoneText);
            node.appendChild(phone);
            root.appendChild(node);
            doc.appendChild(root);

            doc2XmlFile(doc, "e:\\aa.xml");
        } catch (DOMException ex) {
        } catch (ParserConfigurationException ex) {
        } catch (javax.xml.parsers.FactoryConfigurationError ex) {
        }
    }

    /** 将document中的内容写入文件中   */
    public static void doc2XmlFile(Document document, String filename) {
        try {
            FileOutputStream fos = new FileOutputStream(filename);
            OutputFormat of = new OutputFormat("XML", "UTF-8", true);
            XMLSerializer serializer = new XML11Serializer(fos, of);
            serializer.serialize(document.getDocumentElement());
            fos.close();
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
   }

 

 

你可能感兴趣的:(xml)