Java 怎么使用DOM解析器(parser)读取XML文档(Document)

2019年7月29日19:44:43Java 怎么使用DOM解析器(parser)读取XML文档(Document)已关闭评论 689 1776字阅读5分55秒

1.简介

Java 怎么使用DOM解析器(parser)读取XML文档(Document)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.text.NumberFormat;

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.xml.sax.InputSource;

public class ListMoviesXML {
  private static NumberFormat cf = NumberFormat.getCurrencyInstance();

  public static void main(String[] args) {

    Document doc = getDocument("movies.xml");

    Element root = doc.getDocumentElement();

    Element movieElement = (Element) root.getFirstChild();
    Movie m;
    while (movieElement != null) {
      m = getMovie(movieElement);
      String msg = Integer.toString(m.year);
      msg += ": " + m.title;
      msg += " (" + cf.format(m.price) + ")";
      System.out.println(msg);
      movieElement = (Element) movieElement.getNextSibling();
    }
  }

  private static Document getDocument(String name) {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);
      factory.setValidating(true);
      DocumentBuilder builder = factory.newDocumentBuilder();
      return builder.parse(new InputSource(name));
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return null;
  }

  private static Movie getMovie(Element e) {
    
    String yearString = e.getAttribute("year");
    int year = Integer.parseInt(yearString);

    
    Element tElement = (Element) e.getFirstChild();
    String title = getTextValue(tElement).trim();

    
    Element pElement = (Element) tElement.getNextSibling();
    String pString = getTextValue(pElement).trim();
    double price = Double.parseDouble(pString);

    return new Movie(title, year, price);
  }

  private static String getTextValue(Node n) {
    return n.getFirstChild().getNodeValue();
  }

}

class Movie {
  public String title;
  public int year;
  public double price;

  public Movie(String title, int year, double price) {
    this.title = title;
    this.year = year;
    this.price = price;
  }
}

 
继续阅读
编程十万个怎么办