gpt4 book ai didi

java - 使用 xml dom 解析器获取元素

转载 作者:行者123 更新时间:2023-12-01 10:49:55 26 4
gpt4 key购买 nike

如何仅使用 xml DOM 解析器在 jbeil 中获取餐厅名称,请帮忙:这是我的 XML 文件

 <city>

<beirut>
<restaurant>
<name>sada</name>
</restaurant>
</beirut>

<jbeil>
<restaurant>
<name>sada</name>
</restaurant>
</jbeil>

<sour>
<restaurant>
<name>sada</name>
</restaurant>
</sour>

</city>

我想使用 dom 解析器获取 Jbeil 的餐厅名称,此代码为我提供所有城市的餐厅名称:

 try {  
File inputFile = new File("src/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();


NodeList nList = doc.getElementsByTagName("Restaurant");

for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);


if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;


jTextArea1.append( "\n"+"Name : "+ eElement
.getElementsByTagName("name")
.item(0)
.getTextContent()+"\n "

最佳答案

使用 XPath

许多资源:http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/

类似的东西(未测试)

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

XPath xPath =  XPathFactory.newInstance().newXPath();
String expression = "/city/jbeil/restaurant/name";
//read a string value
String thename= xPath.compile(expression).evaluate(xmlDocument);

关于java - 使用 xml dom 解析器获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com