用java解析xml

发布于 2024-11-18 04:11:20 字数 3266 浏览 4 评论 0原文

我是 xml 解析新手,我正在尝试使用 java 解析以下 xml 文件。

<a>
<e class="object">
    <amenities class="array">
        <e class="object">
            <id type="number">31</id>
            <name type="string">Internet access available</name>
        </e>
        <e class="object">
            <id type="number">9</id>
            <name type="string">Business center</name>
        </e>

</amenities>
<brands class="array">
        <e class="object">
            <code type="number">291</code>
            <name type="string">Utell</name>
        </e>
        <e class="object">
            <code type="number">72</code>
            <name type="string">Best Western International</name>
        </e>


</brands>
<hotels class="array">
        <e class="object">
            <addressLine1 type="string">4 Rue du Mont-Thabor</addressLine1>             
            <city type="string">Paris</city>                
            <name type="string">Renaissance Paris Vendome Hotel</name>
            <starRating type="string">5</starRating>                
        </e>
        <e class="object">
            <addressLine1 type="string">35 Rue de Berri</addressLine1>              
            <city type="string">Paris</city>                
            <name type="string">Crowne Plaza Hotel PARIS-CHAMPS ELYSÉES</name>
            <starRating type="string">5</starRating>                
        </e>
</hotels>    

</e>
</a>

我只需要列出我使用以下代码的名称标签信息(这将是酒店名称),但它不仅给我提供了酒店信息,还提供了所有内容,任何人都可以帮我解析这个吗???

多谢!!!

这是我使用的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 ReadXMLFile {

public static void main(String argv[]) { 

 try {

    File fXmlFile = new File("c:\\file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("e");
    System.out.println("-----------------------");

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

       Node nNode = nList.item(temp);       
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;

          System.out.println("Hotel Name : "  + getTagValue("name",eElement));


        }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }

 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 

    return nValue.getNodeValue();    
 }

}

I'm new to xml parsing, I am trying to parse the following xml file using java.

<a>
<e class="object">
    <amenities class="array">
        <e class="object">
            <id type="number">31</id>
            <name type="string">Internet access available</name>
        </e>
        <e class="object">
            <id type="number">9</id>
            <name type="string">Business center</name>
        </e>

</amenities>
<brands class="array">
        <e class="object">
            <code type="number">291</code>
            <name type="string">Utell</name>
        </e>
        <e class="object">
            <code type="number">72</code>
            <name type="string">Best Western International</name>
        </e>


</brands>
<hotels class="array">
        <e class="object">
            <addressLine1 type="string">4 Rue du Mont-Thabor</addressLine1>             
            <city type="string">Paris</city>                
            <name type="string">Renaissance Paris Vendome Hotel</name>
            <starRating type="string">5</starRating>                
        </e>
        <e class="object">
            <addressLine1 type="string">35 Rue de Berri</addressLine1>              
            <city type="string">Paris</city>                
            <name type="string">Crowne Plaza Hotel PARIS-CHAMPS ELYSÉES</name>
            <starRating type="string">5</starRating>                
        </e>
</hotels>    

</e>
</a>

I only need to list the name tag info(which will be the Hotel name) for that I used following code but it resulted me not only the hotel info but also everything, can anyone please help me parsing this???

Thanks a lot!!!

Here is the java code I used

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 ReadXMLFile {

public static void main(String argv[]) { 

 try {

    File fXmlFile = new File("c:\\file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("e");
    System.out.println("-----------------------");

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

       Node nNode = nList.item(temp);       
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;

          System.out.println("Hotel Name : "  + getTagValue("name",eElement));


        }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }

 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 

    return nValue.getNodeValue();    
 }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

勿忘心安 2024-11-25 04:11:20

您可以使用 xpath 获取所有 name 节点:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/hotels//name");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;

You could use xpath to get all the name nodes:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/hotels//name");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
愛放△進行李 2024-11-25 04:11:20

Pavithira 您可以使用 xpath 仅获取酒店,下面是主要方法,您可以简单地复制/粘贴到您的代码中。

public static void main(String argv[]) {
        try {

               File fXmlFile = new File("c:\\file.xml");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        System.out.println("Root element :"
                + doc.getDocumentElement().getNodeName());
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//hotels/e");
        NodeList nList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        System.out.println("-----------------------");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("Hotel Name : "
                        + getTagValue("name", eElement));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

Pavithira you can use xpath to get only the hotels, below is the main method which you can simple copy/paste at your code.

public static void main(String argv[]) {
        try {

               File fXmlFile = new File("c:\\file.xml");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        System.out.println("Root element :"
                + doc.getDocumentElement().getNodeName());
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//hotels/e");
        NodeList nList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        System.out.println("-----------------------");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("Hotel Name : "
                        + getTagValue("name", eElement));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();

    }
眼波传意 2024-11-25 04:11:20

您正在迭代“e”节点,因此循环将打印出任何“e”节点(包括(子)根节点!)内的每个节点。如果您只想检索和打印这些节点,请将 getElementsByTagName 参数更改为“name”。

You are iterating over the 'e' nodes, so your loop will print out every node inside any 'e' node (which includes the (sub)root node!). Change your getElementsByTagName paramater to "name" if you only want to retrieve and print those nodes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文