首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

java中四种操作xml模式

2012-10-30 
java中四种操作xml方式> <RESULT> <VALUE>    <NO>A1234</NO>    <ADDR>四川省XX县XX镇XX路X段XX号</ADDR>

java中四种操作xml方式

<RESULT>
<VALUE>
   <NO>A1234</NO>
   <ADDR>四川省XX县XX镇XX路X段XX号</ADDR>
</VALUE>
<VALUE>
   <NO>B1234</NO>
   <ADDR>四川省XX市XX乡XX村XX组</ADDR>
</VALUE>
</RESULT>

1)DOM

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

public class MyXMLReader{
 public static void main(String arge[]){

  long lasting =System.currentTimeMillis();
  try{
   File f=new File("data_10k.xml");
   DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
   DocumentBuilder builder=factory.newDocumentBuilder();
   Document doc = builder.parse(f);
   NodeList nl = doc.getElementsByTagName("VALUE");
   for (int i=0;i<nl.getLength();i++){
    System.out.print("车牌号码:" + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
    System.out.println("车主地址:" + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
   }
  }catch(Exception e){
   e.printStackTrace();
}

2)SAX

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;

public class MyXMLReader extends DefaultHandler {

 java.util.Stack tags = new java.util.Stack();
 public MyXMLReader() {
  super();
}

 public static void main(String args[]) {
  long lasting = System.currentTimeMillis();
  try {
   SAXParserFactory sf = SAXParserFactory.newInstance();
   SAXParser sp = sf.newSAXParser();
   MyXMLReader reader = new MyXMLReader();
   sp.parse(new InputSource("data_10k.xml"), reader);
  } catch (Exception e) {
   e.printStackTrace();
  }

  System.out.println("运行时间:" + (System.currentTimeMillis() - lasting) + "毫秒");}
  public void characters(char ch[], int start, int length) throws SAXException {
  String tag = (String) tags.peek();
  if (tag.equals("NO")) {
   System.out.print("车牌号码:" + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
  System.out.println("地址:" + new String(ch, start, length));
}
}

  public void startElement(String uri,String localName,String qName,Attributes attrs) {
  tags.push(qName);}
}

    System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());
   }
  } catch (Exception e) {
   e.printStackTrace();
}

}

4)DOM4J

import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;

public class MyXMLReader {

 public static void main(String arge[]) {
  long lasting = System.currentTimeMillis();
  try {
   File f = new File("data_10k.xml");
   SAXReader reader = new SAXReader();
   Document doc = reader.read(f);
   Element root = doc.getRootElement();
   Element foo;
   for (Iterator i = root.elementIterator("VALUE"); i.hasNext() {
    foo = (Element) i.next();
    System.out.print("车牌号码:" + foo.elementText("NO"));
    System.out.println("车主地址:" + foo.elementText("ADDR"));
   }
  } catch (Exception e) {
   e.printStackTrace();
}
)


热点排行