XML是一種基於XML規範語法的標籤類型文檔,它是重量級的,本文主要介紹XML在java語言裏面的生成與解析,XML生成包爲Dom4j,有關XML與其他數據格式之間的比較將會在接下來的文章中給出。
一、生成xml
使用java代碼生成以下xml文檔
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<User name="stryang" sex="男" age="24">
<son>
</son>
</User>
</Root>
java代碼
//java
/** 建立document對象 */
Document document = DocumentHelper.createDocument();
/** 建立config根節點 */
Element configElement = document.addElement("Root");
/** 用戶屬性 */
Element userElement = configElement.addElement("User");
userElement.addAttribute("name", "stryang");
userElement.addAttribute("sex", "男");
userElement.addAttribute("age", "24");
userElement.addElement("son");
將xml文檔轉爲字符串
try {
// 使用輸出流來進行轉化
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 使用GB2312編碼
OutputFormat format = new OutputFormat(" ", true, "utf-8");
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
String s = out.toString("utf-8");
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
二、解析xml
1.從http輸出流裏面獲取xml
public static Document getDocument(String url){
Document doc = null;
HttpURLConnection conn = null;
InputStream ins = null;
SAXReader reader = null;
try{
HttpTimeoutHandler hth = new HttpTimeoutHandler(600000);
URL conURL = new URL(null,url,hth);
conn = (HttpURLConnection)conURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
ins = conn.getInputStream();
reader =new SAXReader();
doc= reader.read(ins);
ins.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ins != null) {
ins.close();
ins = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (conn != null) {
conn.disconnect();
conn = null;
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return doc;
}
2.從Document對象獲取數據,主要涉及到dom4j相關api
- Element.node(index) - 獲得在元素特定索引XML節點。
- Element.attributes() - 獲取一個元素的所有屬性。
- Node.valueOf(@Name) - 得到元件的給定名稱的屬性的值。
- Document.getRootElement() - 得到的XML的根元素。