如何解析 XML 元素根和 select 它在 Java 中的某些值?

How to parse an XML element root an select some values of it in Java?

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

       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>

在我的例子中,我想从 planes_for_sale 根元素加载 idnumname

尝试编组和解组机制

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/

任何正在寻找实用方法的人都可以在这里进行测试:

    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"));
                    }
                 }

使用 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

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

它告诉你如何

  • 将 XML 文件读入 DOM
  • 用XPath筛选出一组节点
  • 对每个提取的节点执行特定操作。

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