`
henry406
  • 浏览: 114338 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

dom XML操作

    博客分类:
  • java
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) {
        }
   }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics