六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 48|回复: 0

java读xml的网站

[复制链接]

升级  82%

292

主题

292

主题

292

主题

进士

Rank: 4

积分
910
 楼主| 发表于 2013-2-5 01:20:51 | 显示全部楼层 |阅读模式
http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
This sample code reads the XML file using DOM [size=1em]parser. DOM parser loads the XML file into the memory and makes an object model of it. This Object modal can be traversed to get its elements.
This code will parse the following MyXMLFile.xml file and print its elements to the console.
XML file: MyXMLFile.xml
<?xml version="1.0"?><company><employee><firstname>Tom</firstname><lastname>Cruise</lastname></employee><employee><firstname>Paul</firstname><lastname>Enderson</lastname></employee><employee><firstname>George</firstname><lastname>Bush</lastname></employee></company><div class="java"><!-- start source code -->import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader {

 public static void main(String argv[]) {

  try {
  File file = new File("c:\\MyXMLFile.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
  NodeList nodeLst = doc.getElementsByTagName("employee");
  System.out.println("Information of all employees");

  for (int s = 0; s < nodeLst.getLength(); s++) {

    Node fstNode = nodeLst.item(s);
    
    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
  
           Element fstElmnt = (ElementfstNode;
      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
      Element fstNmElmnt = (ElementfstNmElmntLst.item(0);
      NodeList fstNm = fstNmElmnt.getChildNodes();
      System.out.println("First Name : "  ((NodefstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
      Element lstNmElmnt = (ElementlstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("Last Name : " ((NodelstNm.item(0)).getNodeValue());
    }

  }
  catch (Exception e) {
    e.printStackTrace();
  }
 }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表