加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:55:54 所属栏目:百科 来源:网络整理
导读: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.No
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就业班培训教程

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读