解析XML
DOM :(Java提供) (整个文件加载到内存中去执行解析)
SAX :(Javat提供) 创建一个Handler类逐个节点的访问解析;个人理解因为不是一次性加载到内存,这个不提供修改保存;
JDOM :通过Stream 流的形式一次性解析加载到内存。和DOM解析类似,即使不知道第一级节点的标签名也能遍历解析; 还可以指定编码解析;
DOM4J :
JDOM 解析
准备工作
// 1 获取SAXBuilder
SAXBuilder saxBuilder = new SAXBuilder();
// 2 将文件使用流的形式装载
FileInputStream books = new FileInputStream("books.xml");
// 3 解析文件到内存
Document document = saxBuilder.build(books);
JDOM解析属性名 和 属性值
private static void jdomParser() throws IOException, JDOMException {
SAXBuilder saxBuilder = new SAXBuilder();
FileInputStream books = new FileInputStream("books.xml");
Document document = saxBuilder.build(books);
Element rootElement = document.getRootElement();
List<Element> children = rootElement.getChildren();
System.out.println(children.size());
for (Element book : children) {
//如果知道属性值的id
Attribute attribute = book.getAttribute("id");
System.out.println("attribute name = " + attribute.getName() + " value =" + attribute.getValue());
//如果不知道属性值的id
List<Attribute> attributes = book.getAttributes();
Attribute attr0 = attributes.get(0);
}
}
JDOM解析 子节点 和 子节点的值
List<Element> children1 = book.getChildren();
System.out.println("children1 nachildren1me = " + children1.size());
...
children1.get(0).getName();
children1.get(0).getValue();
网友评论