下面是要解析的xml文档里面的内容:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <person> <student> <name length="4">jack</name> <age>45</age> <sex>man</sex> </student> <student> <name>bill</name> <age>21</age> <sex>women</sex> </student> </person>
下面我们来用jaxp来对这个文档进行dom解析:
public class JAXPDomParse { private static DocumentBuilderFactory factory; private static DocumentBuilder builder; private static Document doc; @BeforeClass public static void init() { try { factory = DocumentBuilderFactory.newInstance(); builder =factory.newDocumentBuilder(); //解析xml文档,获取文档对象,将其加载到内存中 doc = builder.parse("src/student.xml"); } catch (Exception e) { e.printStackTrace(); } } /** * 读取xml文档中<name>bill</name>中的值 * @throws Exception */ @Test public void readXML1() throws Exception { NodeList list = doc.getElementsByTagName("name"); Node node = list.item(1); String value = node.getTextContent(); System.out.println(value); } /** * 读取xml文档中所包含的所有节点,除了文本节点以外 * @throws Exception */ @Test public void readXML2() throws Exception { NodeList nodes = doc.getElementsByTagName("person"); Node rootNode = nodes.item(0); printChild(rootNode); } /** * 读取xml文档中<name length="4">jack</name>的length的属性值 * @throws Exception */ @Test public void readXML3() throws Exception { NodeList nodes = doc.getElementsByTagName("name"); /* * Node nameNode = nodes.item(0); * 由于Node对象给我们提供获取属性的方法得到的是一个数组,很不方便, * 所以我们将Node对象转换成Element对象,从而使获得属性值变得 * 很方便 */ Element nameNode = (Element) nodes.item(0); String value = nameNode.getAttribute("length"); System.out.println(Integer.parseInt(value)); } /** * 向第一个student节点里面的name与age之间插入一个节点<weight no="xxxx">120</weight> * @throws Exception */ @Test public void addXML() throws Exception { NodeList list = doc.getElementsByTagName("student"); Node node = list.item(0); Element weight = doc.createElement("weight"); weight.setAttribute("no","xxxx"); weight.setTextContent("120"); //获取参考节点 Node ageNode = doc.getElementsByTagName("age").item(0); /* * 如果把节点直接插入到末尾就不用这么麻烦了, * 直接用Node对象的appendChild()就 * ok了。 */ node.insertBefore(weight,ageNode); updateXMLData(); } /** * 删除第一个student节点内的sex节点 */ @Test public void deleteXML() throws Exception { Node sexNode = doc.getElementsByTagName("sex").item(0); sexNode.getParentNode().removeChild(sexNode); updateXMLData(); } /** * 更新第一个student节点内的sex节点的值 */ @Test public void updateXML() throws Exception { Node sexNode = doc.getElementsByTagName("sex").item(0); sexNode.setTextContent("women"); updateXMLData(); } /** * 把更新在内存里的数据写回到xml文档里 */ private void updateXMLData() throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(doc),new StreamResult(new FileOutputStream("src/student.xml"))); } /** * 通过递归的方法打印出根节点的所有子节点 */ private void printChild(Node node) { if(node.getNodeType() == 1) { System.out.println(node.getNodeName()); } NodeList list = node.getChildNodes(); for(int i = 0;i < list.getLength();i++) { printChild(list.item(i)); } } }