古詩詞大全網 - 個性簽名 - 如何用Java讀寫和保存xml文件

如何用Java讀寫和保存xml文件

直接附上源代碼導入Java . io . filewriter;

導入Java . io . io exception;

導入Java . util . iterator;導入org . dom4j . *;

導入org . dom4j . io . XML writer;

公共類DOM 4j sample { public static void main(String[]args){

DOM 4j sample DOM 4j sample = new DOM 4j sample();

document document = DOM 4j sample . create document();

嘗試{

dom4jSample。FileWrite(文檔);

document documentStr = DOM 4j sample。string toxml(" & lt;中國& gt我愛!& lt/中國>);

dom4jSample。XML write(documentStr);

Element legend = dom4jSample。FindElement(文檔);

system . out . println(legend . gettext());

}

捕捉(例外e)

{

}

}

/*

*創建壹個XML文檔

*/

公共文檔createDocument()

{

document document = document helper . create document();

element root = document . add element(" root ");

element author 1 = root . addelement(" Lynch ");

author1.addAttribute("年齡"," 25 ");

author 1 . add attribute(" Country "," China ");

author1.addText("我很棒!");

element author 2 = root . addelement(" Legend ");

author2.addAttribute("年齡"," 25 ");

author2.addAttribute("國家","中國");

author2.addText("我很棒!也是!”);

返回文檔;

}

/*

*通過字符串創建壹個XML文檔

*/

公共文檔StringToXML(String str)拋出DocumentException

{

document document = document helper . parse text(str);

返回文檔;

}

公共元素FindElement(文檔Document)

{

element root = document . getrootelement();

元素圖例= null

for(Iterator I = root . element Iterator(" legend ");I . has next();)

{

legend =(Element)I . next();

}

回歸傳奇;

}

/*

*編寫壹個XML文件

*/

public void FileWrite(Document Document)拋出IOException

{

file writer out = new file writer(" C:/DOM 2j sample . XML ");

document . write(out);

out . close();

}

/*

*編寫壹個XML格式文件

*/

公共void XMLWrite(Document document)拋出IOException

{

XMLWriter writer = new XMLWriter(new FileWriter(" C:/DOM 2 jsamplestr . XML "));

writer.write(文檔);

writer . close();

}

}