在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文件的方式,具体选择哪种方式取决于需求和场景。