JAva読み書きxml dom 4 j

3134 ワード

JAvaではxmlの解析のニーズによく遭遇しますが、公式のdomとsaxの解析のほか、dom 4 jなどの第三者が提供するxmlの解析もあります.ここでは簡単なdemoを書きます.
1.解析xml
/**
	 * @Desc:          /  
	 * @param xmlFilePath    xml    
	 */
	public void showXMLResult(String xmlFilePath){
		Element root = getRootElement(xmlFilePath);
		List<Element> childElements = root.elements(); // book  
		for (Element child : childElements) {
			//         
			System.out.println("id: " + child.attributeValue("id"));

			String tid = child.element("title").attributeValue("tid");
			System.out.println("tid:" + tid);
			//           
			System.out.println("title" + child.elementText("title"));
			System.out.println("author" + child.elementText("author"));
			//              
			System.out.println();
		}
	}
	
	/**
	 * @Desc:       ,     
	 * @param filePath     
	 * @return         xml   
	 */
	public Element getRootElement(String filePath){
		SAXReader reader = new SAXReader();
		File file = new File(filePath);
		try {
			return reader.read(file).getRootElement();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}

読み込んだxmlファイル
<?xml version="1.0" encoding="UTF-8"?> 
<books> 
   <book id="001" b="b2"> 
      <title tid="001_01">Harry Potter</title> 
      <author>J K. Rowling</author> 
   </book> 
   <book id="002"> 
      <title>Learning XML</title> 
      <author>Erik T. Ray</author> 
   </book> 
</books>

2.xmlの生成
/**
	 * @Desc:   demo     
	 * @param targetPath     
	 */
	public void writeXML(String targetPath) {
		Document doc = DocumentHelper.createDocument();
		//      
		Element books = doc.addElement("books");
		//      
		Element book1 = books.addElement("book");
		Element title1 = book1.addElement("title");
		Element author1 = book1.addElement("author");

		Element book2 = books.addElement("book");
		Element title2 = book2.addElement("title");
		Element author2 = book2.addElement("author");

		//         
		book1.addAttribute("id", "001");
		//        
		title1.setText("Harry Potter");
		author1.setText("J K. Rowling");

		book2.addAttribute("id", "002");
		title2.setText("Learning XML");
		author2.setText("Erik T. Ray");

		//          
		OutputFormat format = OutputFormat.createPrettyPrint();
		//       
		format.setEncoding("UTF-8");
		//        File  
		File file = new File(targetPath + File.separator + "books.xml");
		//   XMLWriter  ,                    
		XMLWriter writer;
		try {
			writer = new XMLWriter(new FileOutputStream(file), format);
			//     ,write          Document  
			writer.write(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

tips:
dom 4 jは本当にとても強くて、xmlを解析して生成して、dom 4 j.jarというjarパッケージしか必要ありません!!!
添付jarのダウンロード、スタンプ