JDOM (2) - 讀取XML檔
package jdom;
import org.jdom.*;
import org.jdom.input.*;
import java.io.*;
import java.util.List;
public class ReadFibonacci {
public ReadFibonacci() {
//是否用DTD驗正XML的合法性(true/false)
SAXBuilder bSAB = new SAXBuilder(false);
Document docJdom;
try {
//讀取Fibonacci.xml
docJdom = bSAB.build("C:/Documents and Settings/gecko/jbproject/TIJ/Fibonacci.xml");
//取得xml檔內的root節點-Fibonacci_Numbers
Element root = docJdom.getRootElement();
//新增子節點,內容為"驗證XML",index為6
Element fib = new Element("fibonacci");
fib.setText("驗証XML");
fib.setAttribute("index", "6");
root.addContent(fib);
//取得fibonacci.xml所有子節點內容
List children = root.getChildren("fibonacci");
for(int i=0;i\<children.size();i++){
Element child = (Element)children.get(i);
System.out.println("child: "+i);
System.out.println("Text: "+child.getText());
System.out.println("Attrubute: "+child.getAttribute("index"));
}
}
catch (IOException ex) { ex.printStackTrace(); }
catch (JDOMException ex) { ex.printStackTrace(); }
}
public static void main(String[] args) {
ReadFibonacci read = new ReadFibonacci();
}
}
import org.jdom.*;
import org.jdom.input.*;
import java.io.*;
import java.util.List;
public class ReadFibonacci {
public ReadFibonacci() {
//是否用DTD驗正XML的合法性(true/false)
SAXBuilder bSAB = new SAXBuilder(false);
Document docJdom;
try {
//讀取Fibonacci.xml
docJdom = bSAB.build("C:/Documents and Settings/gecko/jbproject/TIJ/Fibonacci.xml");
//取得xml檔內的root節點-Fibonacci_Numbers
Element root = docJdom.getRootElement();
//新增子節點,內容為"驗證XML",index為6
Element fib = new Element("fibonacci");
fib.setText("驗証XML");
fib.setAttribute("index", "6");
root.addContent(fib);
//取得fibonacci.xml所有子節點內容
List children = root.getChildren("fibonacci");
for(int i=0;i\<children.size();i++){
Element child = (Element)children.get(i);
System.out.println("child: "+i);
System.out.println("Text: "+child.getText());
System.out.println("Attrubute: "+child.getAttribute("index"));
}
}
catch (IOException ex) { ex.printStackTrace(); }
catch (JDOMException ex) { ex.printStackTrace(); }
}
public static void main(String[] args) {
ReadFibonacci read = new ReadFibonacci();
}
}