当前位置: 代码迷 >> J2EE >> JAVA XML配置文件读取有关问题
  详细解决方案

JAVA XML配置文件读取有关问题

热度:72   发布时间:2016-04-22 01:14:27.0
JAVA XML配置文件读取问题
XML文件:
<?xml version="1.0" encoding="GB2312" ?>
<books>
 <book email="aaa">
  <name>aName</name>
  <price>aaaa</price>
 </book>
 <book emaiil="bbb">
  <name>bName</name>
  <price>bbbb</price>
 </book>
</books>



JAVA代码:
import java.io.FileInputStream ;
import java.io.FileNotFoundException ;
import java.io.IOException ;
import java.io.InputStream ;

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

import org.w3c.dom.Document ;
import org.w3c.dom.Element ;
import org.w3c.dom.Node ;
import org.w3c.dom.NamedNodeMap ;
import org.w3c.dom.NodeList ;
import org.xml.sax.SAXException ;

public class ReadXML {

 public ReadXML(){
  //(1)得到DOM解析器的工厂实例
  DocumentBuilderFactory domFac = DocumentBuilderFactory.newInstance() ;
  //得到javax.xml.parsers.DocumentBuilderFactory 类的实例就是我们要解析器工厂
  try{
  //(2)从DOM工厂获取DOM解析器
  DocumentBuilder domBuilder = domFac.newDocumentBuilder() ;
  //通过javax.xml.parsers.DocumentBuilderFactory实例的静态方法newDocumentBuilder()得到DOM解析器
  //(3)把要解析的XML文档转化为输入流,以便DOM解析器解析
  InputStream is = new FileInputStream("config.xml");//文件路径为当前class的最外层包目录
  //(4)解析XML文档的输入流,得到一个Document
  Document doc = domBuilder.parse(is) ;
  //由XML文档的输入流得到一个org.w3c.dom.Document 对象,以后的处理都是对Document对象进行的;
   
  //(5)得到XML文档的根节点
  Element root = doc.getDocumentElement() ;
  //在DOM中只有根节点是一个org.w3c.dom.Element对象
  //(6)得到节点的子节点
  NodeList books = root.getChildNodes() ;
  if (books != null){
  System.out.println("---- len :"+books.getLength() ) ;
  for (int i= 0 ;i<books.getLength(); i++){
  Node book = books.item(i);
  if (book.getNodeType() == Node.ELEMENT_NODE){
  //(7)取得节点属性值
  NamedNodeMap attributes = book.getAttributes();
  for (int j = 0; j < attributes.getLength(); j++) {  
  Node attribute = attributes.item(j);  
  System.out.println("book的属性名为:" + attribute.getNodeName()  
  + " 相对应的属性值为:" + attribute.getNodeValue());  
  }  
  
  //String email = book.getAttributes().getNamedItem("email").getNodeValue() ;
  //System.out.println("E-mail :"+ email) ;
  //注意,节点的属性也是他的子节点,它的节点类型也是Node.ELEMENT_NODE
  System.out.println("----1") ;
  //(8)轮循子节点
  for (Node node= book.getFirstChild(); node != null; node= node.getNextSibling()){
  System.out.println("----2"+node.getNodeName()) ;
  if (node.getNodeType() == Node.ELEMENT_NODE){
  if (node.getNodeName().equals("name")){
String name = node.getNodeValue() ;
String name1 = node.getFirstChild().getNodeValue() ;
System.out.println("这里的name的值是空的:"+name) ;
System.out.println("xml里面的name标签值:"+name1) ;
}
if (node.getNodeName().equals("price")) {
String price = node.getFirstChild().getNodeValue() ;
System.out.println("xml里面的price标签值:"+price) ;
} }
   
  }
  }//(6)这是用一个org.w3c.dom.NodeList接口来存放它所有子节点的,还有一种轮循子节点的额犯法,后面有介绍
  }
  }
  相关解决方案