如何解析XML元素根并在Java中选择它的一些值?

时间:2018-10-15 19:12:33

标签: java xml jdom

我正在寻找一种解析xml根元素并从中获取一些值的实用方法。 我尝试了很多方法,但是没有一种是有效的。

       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

                Document doc = factory.newDocumentBuilder().parse(fileLoaded);

                Element root = null;

                NodeList list = doc.getChildNodes();
               System.out.println(list.toString());
                for (int i = 0; i < list.getLength(); i++) {
                  if (list.item(i) instanceof Element) {
                    root = (Element) list.item(i);
                    System.out.println(root.toString());
                    break;
                  }
                }
                root = doc.getDocumentElement();
              }

XML文件:

    <planes_for_sale id="planeId" num="1452" name="boing">
    <ad>
      <year> 1977 </year>
      <make> test </make>
      <model> Skyhawk </model>
      <color> Light blue and white </color>
      <description> New paint, nearly new interior,
        685 hours SMOH, full IFR King avionics </description>
      <price> 23,495 </price>
      <seller phone = "555-222-3333"> Skyway Aircraft </seller>
      <location>
      <city> Rapid City, </city>
      <state> South Dakota </state>
  </location>

对于我来说,我想从id根元素中加载numnameplanes_for_sale

4 个答案:

答案 0 :(得分:1)

使用XPath提取属性值和元素内容。

    DocumentBuilder builder = DocumentBuilderFactory
                                 .newInstance()
                                 .newDocumentBuilder();

    Document doc = builder.parse(...);

    XPath xp = XPathFactory
                  .newInstance()
                  .newXPath();

    String id = xp.evaluate("planes_for_sale/@id", doc);
    String num = xp.evaluate("planes_for_sale/@num", doc);
    String name = xp.evaluate("planes_for_sale/@name", doc);

    System.out.println("id: " + id);
    System.out.println("num: " + num);
    System.out.println("name: " + name);

产生:

id: planeId
num: 1452
name: boing

答案 1 :(得分:0)

尝试使用编组和解组机制

JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    EmployeeMap empMap = (EmployeeMap) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") );

https://howtodoinjava.com/jaxb/jaxb-example-marshalling-and-unmarshalling-hashmap-in-java/

答案 2 :(得分:0)

对于任何在这里寻求实用方法的人来说,这都是经过考验的:

    DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();

            Document doc = factory.newDocumentBuilder().parse(fileLoaded);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :"
                    + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("planes_for_sale");

              System.out.println("----------------------------");

                 for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                        System.out.println("Plane name : " 
                           + eElement.getAttribute("name"));
                    }
                 }

答案 3 :(得分:0)

看看这个答案 How to read XML using XPath in Java

它向您展示了如何

  • 将XML文件读入DOM
  • 使用XPath过滤掉一组节点
  • 对每个提取的节点执行特定操作。

可以在此处找到具有XPath 2.0支持的变体

How to match string that ends with a number using XPath