XML文件的解析

来源:互联网 发布:网络小说辅助软件 编辑:程序博客网 时间:2024/06/10 03:31

创建一个XML文件放在工程目录下

解析代码:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class AnalysisXMLDemo {

 /**
  * xml文件的解析
  * @param args
  */
 public static void main(String[] args) {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
  try {
   DocumentBuilder builder = factory.newDocumentBuilder() ;
   File file = new File("Mess.xml") ;
   Document document = builder.parse(file) ;
   //获取根节点
   Element root = document.getDocumentElement() ;
   parseElement(root);
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
 
 public static void parseElement(Element element){
  String tagName = element.getTagName() ;
  NodeList child = element.getChildNodes() ;
  System.out.print("<"+tagName);
  
  NamedNodeMap map = element.getAttributes() ;
  
  //如果该元素存在
  if(null != map){
   for (int i = 0; i < map.getLength(); i++) {
    //获得该元素的每一个属性
    Attr attr = (Attr)map.item(i) ;
    String attrName = attr.getName() ;
    String attrValue = attr.getValue() ;
    System.out.print(attrName+":"+attrValue);
   }
  }
  System.out.print(">");
  
  for (int i = 0; i < child.getLength(); i++) {
   Node node = child.item(i) ;
   //获得节点的类型
   short nodeType = node.getNodeType() ;
   if(nodeType == Node.ELEMENT_NODE){
    //是元素继续递归
    parseElement((Element)node);
   }else if(nodeType == Node.TEXT_NODE){
    //递归出口
    System.out.print(node.getNodeValue());
   }else if(nodeType == Node.COMMENT_NODE){
    //是注释内容
    System.out.println("<--");
    Comment comment = (Comment)node ;
    
    //注释内容
    String data = comment.getData() ;
    System.out.print(data+"-->");
   }
  }
  System.out.println("</"+tagName+">");
 }
 
}

 

解析后的输出结果:

<messagename:姓名>
  <title>xml解析</title>

  <body>
   <person>小明</person>

   <detail>信息内容</detail>

  </body>

 </message>

 


 

0 0
原创粉丝点击