java读取xml数据_java如何从xml文件中读取一个值
时间: 2024-05-15 13:13:12 浏览: 89
java 对 xml 文件进行读取
Java可以使用DOM、SAX、JDOM等方式来读取XML文件中的数据。以下是使用DOM方式读取XML文件中某个节点值的示例代码:
```java
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;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXML {
public static void main(String argv[]) {
try {
File inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("book");
Node nNode = nList.item(0);
Element eElement = (Element) nNode;
String title = eElement.getElementsByTagName("title").item(0).getTextContent();
System.out.println("Book title : " + title);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码会读取名为`input.xml`的XML文件中第一个`book`节点的`title`子节点的值,并输出在控制台上。需要注意的是,此示例中的XML文件结构为:
```xml
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
```
如果想要读取其他节点的值,可以将示例代码中的`getElementsByTagName`和`getElementsByTagName`方法中的参数值进行相应修改。
阅读全文