JDOM (1) - 建立XML檔
//建立Fibonacci數列並將結果寫入Fibonacci.xml中
package jdom;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import java.math.BigInteger;
import java.io.FileWriter;
import java.io.IOException;
public class FibonacciJDOM {
public FibonacciJDOM(){
//建立根節點root, Tag名稱為Fibonacci_Numbers
Element root = new Element("Fibonacci_Numbers");
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
for(int i=1;i<=5;i++){
//建立存放費氐樹列的Tag名稱-fibonacci
Element fib = new Element("fibonacci");
fib.setText( low.toString() );
fib.setAttribute("index", String.valueOf(i));
//利用addContent()建根節點與子節點的從屬關係
root.addContent(fib);
BigInteger tmp = high;
high = high.add(low);
low = tmp;
}
//設定root為此XML的根節點
Document doc = new Document();
doc.setRootElement(root);
//用Format.getPrettyFormat()使XML文字內容排列整齊
XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
try {
//輸出內容至console
serializer.output(doc, System.out);
} catch (IOException ex) {System.err.println("ex: "+ex);}
//寫入Fibonacci.xml
FileWriter writer = null;
try {
writer = new FileWriter("Fibonacci.xml");
serializer.output(doc, writer);
writer.close();
} catch (IOException ex1) { ex1.printStackTrace(); }
}
public static void main(String[] args) {
FibonacciJDOM Fib = new FibonacciJDOM();
}
}
package jdom;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import java.math.BigInteger;
import java.io.FileWriter;
import java.io.IOException;
public class FibonacciJDOM {
public FibonacciJDOM(){
//建立根節點root, Tag名稱為Fibonacci_Numbers
Element root = new Element("Fibonacci_Numbers");
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
for(int i=1;i<=5;i++){
//建立存放費氐樹列的Tag名稱-fibonacci
Element fib = new Element("fibonacci");
fib.setText( low.toString() );
fib.setAttribute("index", String.valueOf(i));
//利用addContent()建根節點與子節點的從屬關係
root.addContent(fib);
BigInteger tmp = high;
high = high.add(low);
low = tmp;
}
//設定root為此XML的根節點
Document doc = new Document();
doc.setRootElement(root);
//用Format.getPrettyFormat()使XML文字內容排列整齊
XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
try {
//輸出內容至console
serializer.output(doc, System.out);
} catch (IOException ex) {System.err.println("ex: "+ex);}
//寫入Fibonacci.xml
FileWriter writer = null;
try {
writer = new FileWriter("Fibonacci.xml");
serializer.output(doc, writer);
writer.close();
} catch (IOException ex1) { ex1.printStackTrace(); }
}
public static void main(String[] args) {
FibonacciJDOM Fib = new FibonacciJDOM();
}
}
0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁