Java如何使用JDOM读取XML文档?
此示例提供了一个有关如何使用JDOM解析XML文档,迭代每个元素以及读取元素或属性值的小代码段。要使用此示例,您必须具有JDOM库。您可以从JDOM网站下载它。
package org.nhooo.example.jdom; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import java.io.ByteArrayInputStream; import java.util.List; public class ReadXmlDocument { public static void main(String[] args) { //本示例中要处理的虚构xml文件。 String data = "<root>" + "<row>" + "<column name=\"username\" length=\"16\">admin</column>" + "<column name=\"password\" length=\"128\">secret</column>" + "</row>" + "<row>" + "<column name=\"username\" length=\"16\">jdoe</column>" + "<column name=\"password\" length=\"128\">password</column>" + "</row>" + "</root>"; //创建一个SAXBuilder实例 SAXBuilder builder = new SAXBuilder(); try { //告诉SAXBuilder从中构建Document对象。 //提供了InputStream。 Document document = builder.build( new ByteArrayInputStream(data.getBytes())); //获取我们的xml文档根元素,该元素等于 // <root> tag in the xml document. Element root = document.getRootElement(); // Get all the children named with <row> in the document. //该方法将子级作为java.util.List返回 //目的。 List rows = root.getChildren("row"); for (int i = 0; i < rows.size(); i++) { //将每一行转换为Element对象并获取其 // children which will return a collection of <column> //元素。当我们必须列元素时,我们可以阅读 //如上定义的属性值(名称,长度) // and also read its value (between the <column></column> //标签),方法是调用getText()方法。 // //getAttribute()方法还提供了一种方便的方法 //如果我们想将属性值转换为正确的 //org.nhooo.data类型,在该示例中,我们读取了length属性 //值作为整数。 Element row = (Element) rows.get(i); List columns = row.getChildren("column"); for (int j = 0; j < columns.size(); j++) { Element column = (Element) columns.get(j); String name = column.getAttribute("name").getValue(); String value = column.getText(); int length = column.getAttribute("length").getIntValue(); System.out.println("name = " + name); System.out.println("value = " + value); System.out.println("length = " + length); } } } catch (Exception e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>