JAVA读取XML的方法

DomParser.java

package com.accp.demo.dom;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class DomParser {
public DomParser() {
}

public static void main(String[] args) {
String uri = "src/books.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(uri);
NodeList bookList = doc.getElementsByTagName("book");
for (int i = 0; i < bookList.getLength(); i++) {
String name = doc.getElementsByTagName("name").item(i)
.getFirstChild().getNodeValue();
String author = doc.getElementsByTagName("author").item(i)
.getFirstChild().getNodeValue();
String price = doc.getElementsByTagName("price").item(i)
.getFirstChild().getNodeValue();
System.out.println("name:" + name);
System.out.println("author:" + author);
System.out.println("price:" + price);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


SaxParser.java

package com.accp.demo.sax;

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 SaxParser extends DefaultHandler {
public static void main(String[] args) {
String uri = "src/books.xml";
try {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(false);
parserFactory.setNamespaceAware(false);
SaxParser SaxParserInstance = new SaxParser();
SAXParser parser = parserFactory.newSAXParser();
parser.parse(uri, SaxParserInstance);
} catch (Exception exception) {
exception.printStackTrace();
}
}

public void characters(char[] ch, int start, int length)
throws SAXException {
// System.out.println("ch:" + ch);
// System.out.println("start:" + start);
// System.out.println("length:" + length);
String str = new String(ch, start, length);
if (!str.startsWith("\n")) {
System.out.println("str:" + str);
}
}

public void startDocument() throws SAXException {
System.out.println("开始文档");
}

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// System.out.println("uri---" + uri);
// System.out.println("localName---" + localName);
System.out.println("qName---" + qName);
// System.out.println("attributes---" + attributes);
}

public void endElement(String url, String localName, String qName)
throws SAXException {
// System.out.println("url---" + url);
// System.out.println("localName---" + localName);
// System.out.println("qName---" + qName);

}

public void endDocument() throws SAXException {
System.out.println("结束文档");
}

}

你可能感兴趣的:(java,xml)