依赖jdom.jar
直接粘贴代码
注:ServerInfo对应的是XML中query-item对应的对象
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class XmlUtils {
static String xmlPath = "F:\\metrics\\metric.xml";
//解析XML信息
@SuppressWarnings({ "unchecked", "unused" })
public static List<ServerInfo> getAllInfo() throws FileNotFoundException, JDOMException, IOException {
List<ServerInfo> list = new ArrayList<ServerInfo>();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new FileInputStream(xmlPath));
Element root = document.getRootElement();
List<Element> children = root.getChildren();
for(Element element : children) { //每个element为query-item
ServerInfo info = new ServerInfo();
List<Element> queryInfo = element.getChildren();
for(Element ele : queryInfo) {
String value = ele.getValue();
String name = ele.getName();
switch(name) {
case "id":
info.setId(Integer.parseInt(value));
break;
case "name" :
info.setName(value);
break;
default :
break;
}
list.add(info);
}
}
return list;
}
//更改XML信息
@SuppressWarnings("unchecked")
public static void updateInfo(List<ServerInfo> infos) throws FileNotFoundException, JDOMException, IOException {
Map<String, ServerInfo> idInfoMap = idInfoMap(infos);
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new FileInputStream(xmlPath));
Element root = document.getRootElement();
List<Element> children = root.getChildren();
for(Element element : children) {
String eleId = null;
List<Element> queryInfo = element.getChildren();
for(Element info : queryInfo) {
String value = info.getValue();
String name = info.getName();
if("id".equals(name))
eleId = value;
if("open".equals(name)) {
info.setText(""+idInfoMap.get(eleId).isOpen());
break;
}
}
}
saveXMl(document);
}
//key为xml中的id
private static Map<String, ServerInfo> idInfoMap(List<ServerInfo> infos) {
Map<String, ServerInfo> map = new HashMap<String, ServerInfo>();
for(ServerInfo info : infos) {
map.put(info.getId()+"", info);
}
return map;
}
public static void saveXMl(Document document) throws IOException {
XMLOutputter out = new XMLOutputter();
FileWriter writer = new FileWriter(xmlPath);
Format format = Format.getPrettyFormat();
out.setFormat(format);
out.output(document, writer);
writer.close();
}
public static void main(String[] args) throws Exception {
List<ServerInfo> allInfo = getAllInfo();
for(ServerInfo info :allInfo) {
System.out.println(info.toString());
}
}
}
我自定义的xml结构
<?xml version="1.0" encoding="UTF-8"?>
<query-items>
<query-item>
<id>1</id>
<name>item1</name>
<open>false</open>
</query-item>
<query-item>
<id>2</id>
<name>item2</name>
<open>false</open>
</query-item>
</query-items>