在Java中,可以使用DOM、SAX或者JAXB來讀寫XML文件。下面分別介紹這三種方式的使用方法:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("test.xml"));
Element root = document.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("node");
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String value = element.getTextContent();
System.out.println(value);
}
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean isNode = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("node")) {
isNode = true;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (isNode) {
System.out.println(new String(ch, start, length));
isNode = false;
}
}
};
parser.parse(new File("test.xml"), handler);
JAXBContext context = JAXBContext.newInstance(Node.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Node node = (Node) unmarshaller.unmarshal(new File("test.xml"));
System.out.println(node.getValue());
以上是三種常見的在Java中讀取XML文件的方式,具體選擇哪種方式取決于需求和場景。