当前位置: 首页 > 教程 > Java XML >

Java JDOM解析器 查询XML文档

精华
小牛编辑
137浏览
2023-03-14

Java JDOM解析器 查询XML文档的示例

需要解析的文件input.xml

<?xml version = "1.0"?>
<cars>
    <supercars company = "Ferrari">
        <carname type = "formula one">Ferarri 101</carname>
        <carname type = "sports car">Ferarri 201</carname>
        <carname type = "sports car">Ferarri 301</carname>
    </supercars>

    <supercars company = "Lamborgini">
        <carname>Lamborgini 001</carname>
        <carname>Lamborgini 002</carname>
        <carname>Lamborgini 003</carname>
    </supercars>

    <luxurycars company = "Benteley">
        <carname>Benteley 1</carname>
        <carname>Benteley 2</carname>
        <carname>Benteley 3</carname>
    </luxurycars>
</cars>

编写核心解析处理类

package cn.xnip;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class QueryXmlFileDemo {

   public static void main(String[] args) {

      try {
         File inputFile = new File("input.xml");
         SAXBuilder saxBuilder = new SAXBuilder();
         Document document = saxBuilder.build(inputFile);
         System.out.println("Root element :" + document.getRootElement().getName());
         Element classElement = document.getRootElement();

         List<Element> supercarList = classElement.getChildren("supercars");
         System.out.println("----------------------------");

         for (int temp = 0; temp < supercarList.size(); temp++) {    
            Element supercarElement = supercarList.get(temp);
            System.out.println("\nCurrent Element :" + supercarElement.getName());
            Attribute attribute = supercarElement.getAttribute("company");
            System.out.println("company : " + attribute.getValue() );
            List<Element> carNameList = supercarElement.getChildren("carname");
            
            for (int count = 0; count < carNameList.size(); count++) {	 
               Element carElement = carNameList.get(count);
               System.out.print("car name : ");
               System.out.println(carElement.getText());
               System.out.print("car type : ");
               Attribute typeAttribute = carElement.getAttribute("type");
               
               if(typeAttribute != null)
                  System.out.println(typeAttribute.getValue());
               else {
                  System.out.println("");
               }
            }
         }
      } catch(JDOMException e) {
         e.printStackTrace();
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

输出结果为:

Java JDOM解析器 查询XML文档