以下介紹使用jdom套件的方式,
使用的版本為jdom-2.0.5.jar
首先是xml的資料檔案
<?xml version="1.0" encoding="UTF-8"?> <root> <data> <member> <name>ABC</name> <id>A123456789</id> </member> <member> <name>D123</name> <id>D000000000</id> </member> <member> <name>E1069</name> <id>qwertyuiop</id> </member> </data> <config name="test" vender="T200"> <remark>this is test</remark> </config> </root>
接下來是解析的JAVA檔案,
詳細的API使用可參考註解部分,
package test.jdom;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JdomMethod {
/*
* 將file檔案解析為jdom的Document
*/
public Document saxparser(File file) throws JDOMException, IOException {
return new SAXBuilder().build(file);
}
public void test() throws JDOMException, IOException {
//解析檔案路徑
String path = this.getClass().getClassLoader()
.getResource("/xml/test1.xml").getPath();
File file = new File(path);
//取得從檔案解析的Document
Document doc = saxparser(file);
//取得根路徑
Element root = doc.getRootElement();
//取得data節點
Element data = root.getChild("data");
//取得所有data下member節點的list
List<Element> list = data.getChildren("member");
for (Element member : list) {
//取節點值
System.out.println(member.getChildText("name"));
System.out.println(member.getChildText("id"));
if (member.getChildText("name").equals("E1069")) {
//設定節點值
member.getChild("name").setText("EEEEE");
//移除節點
member.removeChild("id");
}
}
Element config = root.getChild("config");
//取得該元素的屬性值
System.out.println("config.name = " + config.getAttributeValue("name"));
//新增一個屬性值
config.setAttribute(new Attribute("newAttr", "attr1"));
//存回檔案
output(doc, file);
}
/*
* 將修改完成的Document存到File中
*/
public void output(Document doc, File file) throws FileNotFoundException,
IOException {
new XMLOutputter(Format.getPrettyFormat()).output(doc,
new FileOutputStream(file));
}
}
console顯示的訊息---------------------------------------
ABC
A123456789
D123
D000000000
E1069
qwertyuiop
config.name = test
---------------------------------------
最後附上修改完的xml資料
<?xml version="1.0" encoding="UTF-8"?>
<root>
<data>
<member>
<name>ABC</name>
<id>A123456789</id>
</member>
<member>
<name>D123</name>
<id>D000000000</id>
</member>
<member>
<name>EEEEE</name>
</member>
</data>
<config name="test" vender="T200" newAttr="attr1">
<remark>this is test</remark>
</config>
</root>
沒有留言:
張貼留言