[JAVA]XML讀取

來源:互聯網
上載者:User
在java對XML進行處理時,讀取XML文檔,對其處理,這是我得一個執行個體代碼。

import java.io.FileInputStream;
import javax.xml.parsers.*;
import org.w3c.dom.*;

/*
* Created on 2004-6-2
*java讀取XML文檔
*利用DoM來讀取一個XML文檔的內容,並將其列印出來
*/

public class TestXML {

public static void main(String[] args) {
  Document doc;
  DocumentBuilderFactory factory;
  DocumentBuilder docBuilder;
  
   Element root;
   String elementName;
  
  FileInputStream in;
  String fileName;
  try{
   
   //get the xml file
   fileName = System.getProperty("user.dir");
   fileName = fileName+"/sample.xml";
   in = new FileInputStream(fileName);
   
   //解析XML檔案,產生document對象
   factory = DocumentBuilderFactory.newInstance();
   factory.setValidating(false);
   docBuilder = factory.newDocumentBuilder();
   doc = docBuilder.parse(in);
   //解析成功
   System.out.println("parse successfull");
   
   //擷取XML文檔的根節點
   root = doc.getDocumentElement();   
   elementName = root.getNodeName();
   //列印根節點的屬性
   printAttributes(root);
   
   //列印該文檔全部節點
   System.out.println("列印全部節點");
   printElement(root,0);
   
  }
  catch(Exception exp){
   exp.printStackTrace();
  }
}
 
//列印某個節點的全部屬性
public static void printAttributes(Element elem){
  NamedNodeMap attributes;
  int i,max;
  String name,value;
  Node curNode;
  
  attributes = elem.getAttributes();
  max = attributes.getLength();
  
  for(i=0;i<max;i++){
   curNode = attributes.item(i);
   name = curNode.getNodeName();
   value = curNode.getNodeValue();
   System.out.println("/t"+name+" = "+value);
  }
}

//列印所有的節點的名稱和值
//改方法採用遞迴方式列印文檔的全部節點
public static void printElement(Element elem,int depth){
  String elementName;
  NodeList children;
  int i,max;
  Node curChild;
  Element curElement;
  String nodeName,nodeValue;
  
  //elementName = elem.getNodeName();
  //擷取輸入節點的全部子節點
  children = elem.getChildNodes();
  
  //按一定格式列印輸入節點
  for(int j=0;j<depth;j++){
   System.out.print(" ");
  }
  printAttributes(elem);
  
  //採用遞迴方式列印全部子節點
  max = children.getLength();
  for(i=0;i<max;i++){
   
   curChild = children.item(i);
   
   //遞迴允出準則
   if(curChild instanceof Element){
    curElement = (Element)curChild;
    printElement(curElement,depth+1);
   }
   else{
    nodeName = curChild.getNodeName();
    nodeValue = curChild.getNodeValue();
    
    for(int j=0;j<depth;j++)System.out.print(" ");
    System.out.println(nodeName+" = "+nodeValue);
   }
  }
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.