在Java中讀取XML文件內容有多種方法,以下是兩種常見的方法:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class ReadXMLUsingDOM {
public static void main(String[] args) {
try {
File inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("根元素:" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("student");
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
System.out.println("\n當前元素:" + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("學號:" + element.getAttribute("id"));
System.out.println("姓名:" + element.getElementsByTagName("name").item(0).getTextContent());
System.out.println("年齡:" + element.getElementsByTagName("age").item(0).getTextContent());
System.out.println("性別:" + element.getElementsByTagName("gender").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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 ReadXMLUsingSAX {
public static void main(String[] args) {
try {
File inputFile = new File("input.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bName = false;
boolean bAge = false;
boolean bGender = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("name")) {
bName = true;
}
if (qName.equalsIgnoreCase("age")) {
bAge = true;
}
if (qName.equalsIgnoreCase("gender")) {
bGender = true;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("student")) {
System.out.println();
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bName) {
System.out.println("姓名:" + new String(ch, start, length));
bName = false;
}
if (bAge) {
System.out.println("年齡:" + new String(ch, start, length));
bAge = false;
}
if (bGender) {
System.out.println("性別:" + new String(ch, start, length));
bGender = false;
}
}
};
saxParser.parse(inputFile, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
這兩種方法分別使用DOM解析器和SAX解析器來解析XML文件,可以根據需要選擇使用的解析器。