dom解析器getElement

时间:2015-11-28 09:17:46

标签: java xml parsing dom

我想只用dom解析器获得贝鲁特的餐馆请帮忙

这是我的xml文件的一部分:

city - > beirut->餐馆,>餐厅 - >名称 - >

    tyr->restaurants->restaurant->name-> 

    jbeil->restaurants->restaurant->name->

<restaurants>

  <restaurant>

     <name>
     ...

 </restaurant>

</restaurants>

<restaurants>

  <restaurant>

     <name>

     ...

 </restaurant>

</restaurants>

<restaurants>

  <restaurant>

     <name>

     ...

 </restaurant>

</restaurants>

因为这段代码为我提供了所有城市的所有餐厅:

尝试{

 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 "

,我只想要贝鲁特的餐馆请帮忙

1 个答案:

答案 0 :(得分:0)

您使用餐厅,但您的文件使用餐厅。这不好,因为区分大小写。

使用XPath:你可以选择很多东西,它非常易读。

在您的代码中替换它:

XPath xPath = XPathFactory.newInstance().newXPath();
String expression="/city/beirut/restaurants/restaurant";

NodeList nList = (NodeList)  xPath.compile(expression).evaluate(document, XPathConstants.NODESET);