xml相關

public class TXML{
   public static void main(String[] args) {
       try {
           File file = new File("d:/test.xml");
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = factory.newDocumentBuilder();
           Document doc = builder.parse(file);
           NodeList nodeList = doc.getElementsByTagName("dataset");
           for (int i = 0; i < nodeList.getLength(); i++) {
               //System.out.println(doc.getElementsByTagName("bb_cargo_no").item(i).getFirstChild().getNodeValue());
               //System.out.println(doc.getElementsByTagName("bb_operate_date").item(i).getFirstChild().getNodeValue());
           }
           //這種方法比dom解析xml文件更高效;dom解析會把xml文件解析爲一個樹結構,如果大數據非常佔用資源。
           SAXReader reader = new SAXReader();
           org.dom4j.Document xmlDoc=reader.read(file);
           Element root = xmlDoc.getRootElement();
           Iterator ee = root.elementIterator();
           while(ee.hasNext()) {
               Element ww = (Element) ee.next();
               //System.out.println(ww.getName()+","+ww.getData());
           }

       } catch (ParserConfigurationException e) {
           e.printStackTrace();
       } catch (SAXException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } catch (DocumentException e) {
           e.printStackTrace();
       }
       TXML.writeDocument(TXML.getDocument(), "d:/a.xml");  
   }

    public static org.dom4j.Document getDocument(){          
       org.dom4j.Document document = DocumentHelper.createDocument();
        //生成一個接點
       Element root = document.addElement("root");
        //生成root的一個接點
       Element category = root.addElement("category");
       Element name = root.addElement("name");
       //生產category的一個接點
       Element id = category.addElement("id");
       Element username = name.addElement("username");
       //生成id裏面的參數值
       id.addAttribute("name", "id");
       username.addAttribute("name", "username");
       //生成id裏面的值
       id.addText("1");
       username.addText("張三");
       return document;
   }

    public static void writeDocument(org.dom4j.Document document, String outFile){
        try{
            //讀取文件
            FileWriter fileWriter = new FileWriter(outFile);
            //設置文件編碼
            OutputFormat xmlFormat = new OutputFormat();
            xmlFormat.setEncoding("UTF-8");
            //創建寫文件方法
            XMLWriter xmlWriter = new XMLWriter(fileWriter,xmlFormat);
            //寫入文件
            xmlWriter.write(document);
            //關閉
            xmlWriter.close();
        }catch(IOException e){
            System.out.println("文件沒有找到");
            e.printStackTrace();
        }
    }  
}

http://shop107857222.taobao.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章