如何使用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 "
答案 0 :(得分:1)
使用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);
答案 1 :(得分:0)
使用与您相同的代码样式和“仅使用xml DOM解析器”获取<table border="1" >
<tr>
<th>G2B Code</th>
<th>Label</th>
<th>API Code</th>
</tr>
<tr ng-repeat="customer in row.entity.customer">
<td>{{customer.g2bCode}}</td>
<td>{{customer.label}}</td>
<td>{{customer.apiCode}}</td>
</tr>
</table>
然后jbeil
...
restaurant
但我会选择XPath答案......