XML相关操作(Java)


1 XML文件创建示例

import java.io.File;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXML {

    public static void main(String[] args) {
        
        try {
            //DOM
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            
            //创建Languages标签
            Element root = document.createElement("Languages");
            root.setAttribute("cat", "it");     //设置Languages标签的属性
            
            //-----接下来创建Languages标签下的三个子标签lan1、lan2、lan3
            //lan1
            Element lan1 = document.createElement("lan");   //lan标签
            lan1.setAttribute("id", "1");
            Element name1 = document.createElement("name"); //name标签
            name1.setTextContent("Java");
            Element ide1 = document.createElement("ide");   //ide标签
            ide1.setTextContent("Eclipse");
            lan1.appendChild(name1);    //name为lan的子标签
            lan1.appendChild(ide1);     //ide为lan的子标签
            
            //同lan1
            Element lan2 = document.createElement("lan");
            lan2.setAttribute("id", "2");
            Element name2 = document.createElement("name");
            name2.setTextContent("Swift");
            Element ide2 = document.createElement("ide");
            ide2.setTextContent("Xcode");
            lan2.appendChild(name2);
            lan2.appendChild(ide2);
            
            //同lan1
            Element lan3 = document.createElement("lan");
            lan3.setAttribute("id", "3");
            Element name3 = document.createElement("name");
            name3.setTextContent("C#");
            Element ide3 = document.createElement("ide");
            ide3.setTextContent("Visual Studio");
            lan3.appendChild(name3);
            lan3.appendChild(ide3);
            
            
            root.appendChild(lan1);         //lan1、lan2、lan3为root的子标签
            root.appendChild(lan2);
            root.appendChild(lan3);
            
            document.appendChild(root);     //root为document的子标签
            
            
            //----输出
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            StringWriter writer = new StringWriter();
            //文本输出
            transformer.transform(new DOMSource(document), new StreamResult(writer));
            System.out.println(writer.toString());
            //转换成文件
            transformer.transform(new DOMSource(document), new StreamResult(new File("languages.xml")));
            
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

代码运行效果如下:


2 XML文件读取示例

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadXML {

    public static void main(String[] args) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new File("languages.xml"));
            
            //根元素
            Element root = document.getDocumentElement();
            
            //lan标签
            NodeList list = root.getElementsByTagName("lan");
            for(int i=0;i<list.getLength();i++) {
                Element lan = (Element) list.item(i);
                System.out.println("--------------");
                System.out.println("id="+lan.getAttribute("id"));   //输出标签属性
                
                //lan标签下的子标签
                NodeList clist = lan.getChildNodes();
                for (int j = 0; j < clist.getLength(); j++) {
                    Node c = clist.item(j);
                    if(c instanceof Element) {      //节点为Element才输出,否则会读取到换行等
                        System.out.println(c.getNodeName()+"="+c.getTextContent());
                    }
                }
            }
            
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

代码运行效果:


3 Dom4j创建XML

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

public class TestDom4j {
    public static void main(String[] args) {
        String xmlstring = "<root><people>Hov</people></root>";
        try {
            Document document = DocumentHelper.parseText(xmlstring);
            System.out.println(document.asXML());
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

代码运行效果:


 
comments powered by Disqus