•   欢迎来到21NN网.
  •   请记住本站网址www.21nn.cn

Java中剖析XML的体式格局有哪些【XML教程】,Java,解析XML

摘要: java剖析XML的体式格局有运用DOM剖析经由历程DOM对象以树状构造衔接在一起;运用SAX剖析它是碰到差别元素时会逐行剖析;运用StAX剖析会从XML中提取所需的数据XML是一种通用的数...
java剖析XML的体式格局有运用DOM剖析经由历程DOM对象以树状构造衔接在一起;运用SAX 剖析它是碰到差别元素时会逐行剖析;运用StAX剖析会从XML中提取所需的数据

XML是一种通用的数据交换花样,它的平台无关性、言语无关性、体系无关性、给数据集成与交互带来了极大的轻易。接下来将要在文章中为人人细致引见在Java中剖析XML的体式格局,具有肯定的参考作用,愿望对人人有所协助

【引荐课程:XML教程

运用DOM剖析

DOM剖析器重要用于在内存中运用XML作为对象图(树状构造) 也就是文档对象模子(DOM)。起首剖析器遍历输入XML文件并建立与XML文件中的节点相对应的DOM对象。这些DOM对象以树状构造链接在一起。一旦剖析器完成了剖析历程,就会从中取得这个相似树的DOM对象构造。

例:在所有代码示例中剖析xml内容

public class DOMParserDemo {
 
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document =
      builder.parse(
        ClassLoader.getSystemResourceAsStream("xml/employee.xml"));
    List<Employee> empList = new ArrayList<>();
    NodeList nodeList = document.getDocumentElement().getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
      Node node = nodeList.item(i);
      if (node instanceof Element) {
        Employee emp = new Employee();
        emp.id = node.getAttributes().
            getNamedItem("id").getNodeValue();
        NodeList childNodes = node.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
          Node cNode = childNodes.item(j);
          if (cNode instanceof Element) {
            String content = cNode.getLastChild().
                getTextContent().trim();
            switch (cNode.getNodeName()) {
              case "firstName":
                emp.firstName = content;
                break;
              case "lastName":
                emp.lastName = content;
                break;
              case "location":
                emp.location = content;
                break;
            }
          }
        }
        empList.add(emp);
      }
    }
   
    for (Employee emp : empList) {
      System.out.println(emp);
    }
 
  }
}
class Employee{
  String id;
  String firstName;
  String lastName;
  String location;
 
  @Override
  public String toString() {
    return firstName+" "+lastName+"("+id+")"+location;
  }
}

输出效果为:

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

运用SAX 剖析

SAX Parser与DOM剖析器的差别之处在于SAX剖析器不会将完全的XML加载到内存中,而是在碰到差别的元素时,它逐行剖析XML,c触发差别的事宜,比方:翻开标记,完毕标记,字符数据,批评等。

运用SAX Parser剖析XML的代码以下:

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserDemo {
  public static void main(String[] args) throws Exception {
    SAXParserFactory parserFactor = SAXParserFactory.newInstance();
    SAXParser parser = parserFactor.newSAXParser();
    SAXHandler handler = new SAXHandler();
    parser.parse(ClassLoader.getSystemResourceAsStream("xml/employee.xml"),
                 handler);
    for ( Employee emp : handler.empList){
      System.out.println(emp);
    }
  }
}
class SAXHandler extends DefaultHandler {
 
  List<Employee> empList = new ArrayList<>();
  Employee emp = null;
  String content = null;
  @Override
  public void startElement(String uri, String localName,
                           String qName, Attributes attributes)
                           throws SAXException {
       
    switch(qName){
      case "employee":
        emp = new Employee();
        emp.id = attributes.getValue("id");
        break;
    }
  }
 
  @Override
  public void endElement(String uri, String localName,
                         String qName) throws SAXException {
   switch(qName){
     case "employee":
       empList.add(emp);      
       break;
     case "firstName":
       emp.firstName = content;
       break;
     case "lastName":
       emp.lastName = content;
       break;
     case "location":
       emp.location = content;
       break;
   }
  }
 
  @Override
  public void characters(char[] ch, int start, int length)
          throws SAXException {
    content = String.copyValueOf(ch, start, length).trim();
  }
     
}
 
class Employee {
  String id;
  String firstName;
  String lastName;
  String location;
 
  @Override
  public String toString() {
    return firstName + " " + lastName + "(" + id + ")" + location;
  }
}

输出效果为:

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

运用StAX Parser

StAX用于XML的Streaming API,而StAX Parser与SA的差别之处在于SAX Parser。StAX剖析器也是一种与SAX剖析器也是有所差别的

SAX Parser会推送数据,但StAX剖析器会从XML中提取所需的数据。StAX剖析器将光标维持在文档中的当前位置,许可提取光标处可用的内容,而SAX剖析器在碰到某些数据时发出事宜。

XMLInputFactory和XMLStreamReader是可用于加载XML文件的两个类。当我们运用XMLStreamReader读取XML文件时,事宜以整数值的情势生成,然后将这些事宜与XMLStreamConstants中的常量举行比较。以下代码显现了怎样运用StAX剖析器剖析XML:

import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
 
public class StaxParserDemo {
  public static void main(String[] args) throws XMLStreamException {
    List<Employee> empList = null;
    Employee currEmp = null;
    String tagContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader =
        factory.createXMLStreamReader(
        ClassLoader.getSystemResourceAsStream("xml/employee.xml"));
         
    while(reader.hasNext()){
      int event = reader.next();
      switch(event){
        case XMLStreamConstants.START_ELEMENT:
          if ("employee".equals(reader.getLocalName())){
            currEmp = new Employee();
            currEmp.id = reader.getAttributeValue(0);
          }
          if("employees".equals(reader.getLocalName())){
            empList = new ArrayList<>();
          }
          break;
           
        case XMLStreamConstants.CHARACTERS:
          tagContent = reader.getText().trim();
          break;
           
        case XMLStreamConstants.END_ELEMENT:
          switch(reader.getLocalName()){
            case "employee":
              empList.add(currEmp);
              break;
            case "firstName":
              currEmp.firstName = tagContent;
              break;
            case "lastName":
              currEmp.lastName = tagContent;
              break;
            case "location":
              currEmp.location = tagContent;
              break;
          }
          break;
        case XMLStreamConstants.START_DOCUMENT:
          empList = new ArrayList<>();
          break;
      }
 
    }
    for ( Employee emp : empList){
      System.out.println(emp);
    }
       
  }
}
 
class Employee{
  String id;
  String firstName;
  String lastName;
  String location;
   
  @Override
  public String toString(){
    return firstName+" "+lastName+"("+id+") "+location;
  }
}

输出效果为:

Rakesh Mishra(111) Bangalore
John Davis(112) Chennai
Rajesh Sharma(113) Pune

总结:以上就是本篇文章的全部内容了,愿望对人人有所协助

以上就是Java中剖析XML的体式格局有哪些的细致内容,更多请关注ki4网别的相干文章!

分享到:

发表评论

评论列表

还没有评论,快来说点什么吧~

公众号二维码

微信公众号