掌握XML解析:深入比较Java中的四种解析方式
warning:
这篇文章距离上次修改已过180天,其中的内容可能已经有所变动。
在Java中,有四种主要的XML解析方式:
- 使用DOM解析器
- 使用SAX解析器
- 使用JDOM解析器
- 使用DOM4J解析器
以下是每种解析器的简单示例代码:
- 使用DOM解析器:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DOMParserExample {
public static void main(String[] args) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse("example.xml");
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Student");
for (int temp = 0; temp < nList.getLength(); temp++) {
org.w3c.dom.Node node = nList.item(temp);
Element fstElmnt = (Element) node;
System.out.println("First Name : " + getTagValue("firstname", fstElmnt));
System.out.println("Last Name : " + getTagValue("lastname", fstElmnt));
System.out.println("Nick Name : " + getTagValue("nickname", fstElmnt));
System.out.println("Marks : " + getTagValue("marks", fstElmnt));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
}
- 使用SAX解析器:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class SAXParserExample extends DefaultHandler {
boolean bFirstName = false;
boolean bLastName = false;
boolean bNickName = false;
boolean bMarks = false;
public static void main(String[] args) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new SAXParserExample();
saxParser.parse("example.xml", handler);
评论已关闭