1. 程式人生 > >java中的xml操作

java中的xml操作

(1)使用java讀取XML檔案: DOM解析XML

XML樣例如下:(language.xml)

<?xml version="1.0"encoding="UTF-8"?>

<Languages cat="it">

  <lan id="1">

     <name>java</name>

     <ide>eclipse</ide>

  </lan>

  <lan id="2">

     <name>swift</name>

     <ide>Xcode

</ide>

  </lan>

  <lan id="3">

     <name>C#</name>

     <ide>Visual Studio</ide>

  </lan>

</Languages>

解析方式如下:

//DOM解析XML(用try catch

DocumentBuilderFactoryfactory = DocumentBuilderFactory.newInstance();

                DocumentBuilder builder = factory

.newDocumentBuilder();

                Document doc = builder.parse("language.xml");

                Element root = (Element) doc.getDocumentElement();

                System.out.println("cat = "+root.getAttribute("cat"));

                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"));·

//  Element name = (Element)lan.getElementsByTagName("name").item(0);

//                 System.out.println(name.getTextContent());

//  Element ide = (Element)lan.getElementsByTagName("ide").item(0);

//                 System.out.println(ide.getTextContent());

                   NodeList cList = lan.getChildNodes();

                    for(int j = 0;j<=cList.getLength();j++){

                       Node e = cList.item(j);

                       if(e instanceof Element) {

                System.out.println(e.getNodeName()+"="+e.getTextContent());

                       }

                   }

                }

執行結果:

cat = it

-----------------

id=1

name=java

ide=eclipse

-----------------

id=2

name=swift

ide=Xcode

-----------------

id=3

name=C#

ide=Visual Studio

(2)使用java建立XML資料:

public static void main(String[] args) {

          try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            Document document = builder.newDocument();

            Element root = document.createElement("language");

            root.setAttribute("cat", "it");

            Element lan1 = document.createElement("lan");

            lan1.setAttribute("id", "1");

            Element name1 = document.createElement("name");

            name1.setTextContent("java");

            Element ide1 = document.createElement("ide");

            ide1.setTextContent("eclipse");

            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");

            Element lan3 = document.createElement("lan");

            lan3.setAttribute("id", "3");

            Element name3 = document.createElement("name");

            name3.setTextContent("C#");

            Element ide3 = document.createElement("ide");

            ide3.setTextContent("visualStudio");

            lan1.appendChild(name1);

            lan1.appendChild(ide1);

            root.appendChild(lan1);

            lan2.appendChild(name2);

            lan2.appendChild(ide2);

            root.appendChild(lan2);

            lan3.appendChild(name3);

            lan3.appendChild(ide3);

            root.appendChild(lan3);

            document.appendChild(root) ;          

            //---------將當前文件轉化成字串顯示----------------------

            try {

                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("111.xml")));

            } catch (TransformerConfigurationException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (TransformerException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        } catch (ParserConfigurationException e) {

            e.printStackTrace();

        }

    }

執行後,重新整理專案(F5)就會發現專案中建立了111.xml檔案,在控制檯也有輸出。建立好的檔案沒有格式,全選內容,用ctrl+I快捷鍵格式化資料,就可以看到有層次感的xml檔案。

如下所示:

<?xml version="1.0"encoding="UTF-8" standalone="no"?>

<language cat="it">

    <lan id="1">

        <name>java</name>

        <ide>eclipse</ide>

    </lan>

    <lan id="2">

        <name>swift</name>

        <ide>Xcode</ide>

    </lan>

    <lan id="3">

        <name>C#</name>

        <ide>visualStudio</ide>

    </lan>

</language>

(3)使用DOM4J操作xml資料:

在專案中新建一個lib資料夾。將dom4j下載並解壓,解壓後的dom4j-1.6.jar拷貝在工程目錄Lib資料夾下。在main()中:

String xmlString = “ <lan><name>java</name><ide>eclipse</ide></lan>”

 Document doc=DocumentHelper.pareseText(xmlString);

System.out.println(document.asXML));

若需要了解其他的用法,開啟解壓後的/doc/index就可以檢視完整的操作說明。