使用JDOM的步骤
以下是使用JDOM Parser解析文档时使用的步骤.
导入与XML相关的包.
创建SAXBuilder
从文件或流创建文档
提取根元素
检查属性
检查子元素
导入与XML相关的包
import java.io. *; import java.util.*; import org.jdom2.*;
创建一个DocumentBuilder
SAXBuilder saxBuilder = new SAXBuilder();
从文件或流创建文档
File inputFile = new File("input.txt");SAXBuilder saxBuilder = new SAXBuilder();Document document = saxBuilder.build(inputFile);
提取根元素
Element classElement = document.getRootElement();
检查属性
//returns specific attributegetAttribute("attributeName");
检查子元素
//returns a list of subelements of specified namegetChildren("subelementName"); //returns a list of all child nodesgetChildren(); //returns first child nodegetChild("subelementName");
演示示例
以下是我们需要解析的输入xml文件;
dinkar kad dinkar 85 Vaneet Gupta vinni 95 jasvir singn jazz 90
DomParserDemo.java
import java.io.File;import java.io.IOException;import java.util.List;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;public class JDomParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); ListstudentList = classElement.getChildren(); System.out.println("----------------------------"); for (int temp = 0; temp < studentList.size(); temp++) { Element student = studentList.get(temp); System.out.println("\nCurrent Element :" + student.getName()); Attribute attribute = student.getAttribute("rollno"); System.out.println("Student roll no : " + attribute.getValue() ); System.out.println("First Name : " + student.getChild("firstname").getText()); System.out.println("Last Name : " + student.getChild("lastname").getText()); System.out.println("Nick Name : " + student.getChild("nickname").getText()); System.out.println("Marks : " + student.getChild("marks").getText()); } } catch(JDOMException e) { e.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } }}
这会产生以下结果 :
Root element :class----------------------------Current Element :studentStudent roll no : 393First Name : dinkarLast Name : kadNick Name : dinkarMarks : 85Current Element :studentStudent roll no : 493First Name : VaneetLast Name : GuptaNick Name : vinniMarks : 95Current Element :studentStudent roll no : 593First Name : jasvirLast Name : singnNick Name : jazzMarks : 90