我编写了一个 XML 文件,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Library name="StreetCorner">
<Book name="HarryPotter">
<Author name="JKRowling"/>
</Book>
<Book name="SherlockHolmes">
<Author name="SirAConandoyle"/>
</Book>
<Book name="AngelsAndDemons">
<Author name="DanBrown"/>
</Book>
</Library>
阅读本文的最简单方法是什么?
我需要获取图书馆名称、该图书馆中的所有书籍以及写该书的作者姓名。
我已经有一个名为 Library 的模型,因此如果我可以在每次解析时提取数据,我就可以将值设置到 Library 对象上。
name
是我的 xml 中每个元素的属性。
最佳答案
在 Java 中从 XML 文件获取信息的一种方法是使用 Java XML DOM 解析器。
你开始于:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
然后访问加载的数据:
Element root = document.getDocumentElement();
root.getElementsByTagName("Book")
您可以找到完整的教程 here 。这种方法的最大缺点是您将整个文档加载到内存中,但这对您来说不是问题。
其他内置选项包括:
- SAX 解析器
- JAXP
您可以在 this document 中找到这些选项的详细说明。 。讨论了更多选项 in this question .
关于java - 如何读取包含多个元素的 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27148642/