XML文档解析 : doc/sax
dom和sax解析方式的区别:
1.dom解析的优点是对文档的crud比较方便,缺点是占用内存比较大
2.sax解析的优点是占用内存少,解析速度快,缺点是只适合做文档的读取,不适合做文档的crud。
调整jvm大小(默认64M):
-Xmx80m
//使用dom方式对xml进行crud
//使用dom方式对xml进行crud
public class demo3 {
//得到xml文档中的标签
@Test
public void read1() throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse("src/book.xml");
NodeList nl = doc.getElementsByTagName("title");
Node node = nl.item(0);
String content1 = node.getNodeName();
System.out.println(content1);
}
//得到xml文档中所有标签
@Test
public void read2() throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("src/book.xml");
NodeList ll = doc.getElementsByTagName("booklist");
Node node = ll.item(0);
List(node);
}
private void List(Node node)
{
if(node instanceof Element )
{
System.out.println(node.getNodeName());
}
NodeList nl = node.getChildNodes();
for(int i =0; i<nl.getLength();i++)
{
Node nod = nl.item(i);
List(nod);
}
}
//得到xml文档中标签属性的值<书名 id="a1">中的a1
@Test
public void read3() throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("src/book.xml");
Node node = doc.getElementsByTagName("title").item(0);
Element el = (Element)node;
System.out.println(el.getAttribute("id"));
}
}