xml解析技术概述和使用Jaxp对xml文档进行dom解析

前端之家收集整理的这篇文章主要介绍了xml解析技术概述和使用Jaxp对xml文档进行dom解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package cn.itcast.xml;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;




import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


//使用dom方式对xml文档进行crud
public class Demo3 {


@Test
public void read1() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/book1.xml");

NodeList list = document.getElementsByTagName("书名");
Node node = list.item(0);
String content = node.getTextContent();
System.out.println(content);
}
@Test
public void read2() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/book1.xml");

//得到根节点
Node root = document.getElementsByTagName("书架").item(0);
list(root);
}
//得到xml文档 的所有标签
private void list(Node node){
// System.out.println(node.getNodeName());
// NodeList list = node.getChildNodes();
// for(int i=0;i<list.getLength();i++){
// Node child = list.item(i);
// list(child);
// }
if(node instanceof Element){
System.out.println(node.getNodeName());
}
NodeList list = node.getChildNodes();
for(int i=0;i<list.getLength();i++){
Node child = list.item(i);
list(child);
}
}
//得到xml文档 的标签属性的值
@Test
public void read3() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/book1.xml");

Element bookname = (Element) document.getElementsByTagName("书名").item(0);
String value = bookname.getAttribute("name");
System.out.println(value);
}

}


书架 书 书名 作者 售价 书 书名 作者 售价 Java就业班培训教程

原文链接:https://www.f2er.com/xml/298905.html

猜你在找的XML相关文章