Java創建XML的三種方式


1.使用Document創建XML文檔:

注意:導包時導入org.w3c.dom的包:

創建圖書列表:

Book book1 = new Book(1, "001", "魔戒");
book1.addAuthor("托爾金");
Book book2 = new Book(2, "002", "哈利波特");
book2.addAuthor("JK 羅琳");
Book book3 = new Book(3, "004", "冰與火之歌");
book3.addAuthor("喬治馬丁");
		
Book book4 = new Book(4, "009", "三體");
book4.addAuthor("劉慈欣");
book4.addAuthor("楊宇昆");
		
List<Book> list = new ArrayList<>();
list.add(book1);
list.add(book2);
list.add(book3);
list.add(book4);

使用Document創建XML文檔:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			
Element bookList = doc.createElement("book-list");
for (Book b : list) {
	Element book = doc.createElement("book");
	Attr attr = doc.createAttribute("id");
	attr.setValue(String.valueOf(b.getId()));
				
	//為Book標簽添加屬性ID
	book.setAttributeNode(attr);
				
	Element title = doc.createElement("title");
	title.appendChild(doc.createTextNode(b.getTitle()));
	Element isbn = doc.createElement("isbn");
	isbn.appendChild(doc.createTextNode(b.getIsbn()));
	Element authorList = doc.createElement("author-list");
				
	for (String string : b.getAuthors()) {
		Element author = doc.createElement("author");
		author.appendChild(doc.createTextNode(string));
		authorList.appendChild(author);
	}
				
	book.appendChild(title);
	book.appendChild(isbn);
	book.appendChild(authorList);
	bookList.appendChild(book);
}
			
doc.appendChild(bookList);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(new File("doc.xml")));

輸出結果:

使用Document解析XML文檔:

String file = "doc.xml";
List<Book>list = new ArrayList<Book>();
Document doc = DocumentBuilderFactory.newInstance()
		.newDocumentBuilder().parse(new File(file));
NodeList books = doc.getElementsByTagName("book");
for(int i=0;i<books.getLength();i++) {
	Book b = new Book();
	Element book = (Element) books.item(i);
	String id = book.getAttribute("id");
	
	Element title = (Element) book.getElementsByTagName("title").item(0);
	Element isbn = (Element) book.getElementsByTagName("isbn").item(0);
	NodeList authors = book.getElementsByTagName("author-list");
	for(int j=0;j<authors.getLength();j++) {
		Element author = (Element) authors.item(j);
		b.addAuthor(author.getTextContent());
	}
	
	b.setId(Integer.valueOf(id));
	b.setTitle(title.getTextContent());
	b.setIsbn(isbn.getTextContent());
	list.add(b);
}

for (Book book : list) {
	System.out.println(book);
}

轉換后輸出結果:

 

2.使用SAXParse解析XML文檔:

注意:導入包時需注意,導入simple的包:

main方法:

SAXParser parser = SAXParserFactory.newInstance()
		.newSAXParser();
BookHandler bookHandler = new BookHandler();
			
parser.parse(new File("doc.xml"), bookHandler);
			
List<Book>list = bookHandler.list;
for (Book book : list) {
	System.out.println(book);
}

System.out.println("完成");

bookHandler類()

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
	super.startElement(uri, localName, qName, attributes);
	if(qName.equals("book")) {
		book = new Book();
		book.setId(Integer.valueOf(attributes.getValue("id")));
	}
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
	super.endElement(uri, localName, qName);
	if(qName.equals("book")) {
		list.add(book);
	}
	
	if(qName.equals("title")) {
		book.setTitle(text);
	}
	
	if(qName.equals("isbn")) {
		book.setIsbn(text);
	}
	
	if(qName.equals("author")) {
	     book.addAuthor(text);
	}
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
	super.characters(ch, start, length);
	text = String.valueOf(ch,start,length);
}

測試結果:

Book [id=1, isbn=001, title=魔戒, authors=[托爾金]]
Book [id=2, isbn=002, title=哈利波特, authors=[JK 羅琳]]
Book [id=3, isbn=004, title=冰與火之歌, authors=[喬治馬丁]]
Book [id=4, isbn=009, title=三體, authors=[劉慈欣, 楊宇昆]]
完成

3.使用Simple解析XML文檔:

main方法:

Book book1 = new Book(1, "001", "魔戒");
book1.addAuthor("托爾金");
Book book2 = new Book(2, "002", "哈利波特");
book2.addAuthor("JK 羅琳");
Book book3 = new Book(3, "004", "冰與火之歌");
book3.addAuthor("喬治馬丁");

Book book4 = new Book(4, "009", "三體");
book4.addAuthor("劉慈欣");
book4.addAuthor("楊宇昆");

BookList list = new BookList();
list.add(book1);
list.add(book2);
list.add(book3);
list.add(book4);
		
//持久化
Persister persister = new Persister();
try {
	persister.write(list, System.out);
} catch (Exception e) {
	e.printStackTrace();
}

使用注解為Book實體標注:

@Attribute
private int id;

@Element(required = false)
private String isbn;

@Element(required = false)
private String title;

@ElementList(name = "author-list")
private ArrayList<String>authors = new ArrayList<String>();

上述注解含義:

  • Attribute:標注該字段為標簽中的屬性
  • Element:標注該字段為元素
  • ElementList:標注為元素列表
  • required:標注是否為可選屬性(true:必須有(默認為true);false:可有可無)
  • name:修改字段在標簽中的名字
  • root:標注該字段為XML的根

BookList類(為ArrayList做了一下包裝)

@Root(name = "book-list")
public class BookList {
	
	@ElementList(name = "book",inline = true)
	ArrayList<Book>bookList;
	
	public BookList() {
		bookList = new ArrayList<Book>();
	}
	
	public void add(Book book) {
		bookList.add(book);
	}
}

注意:ArrayList為官方寫好的,我們是不可以改變的,也就不可以為其添加注解,所以采用一個包裝的方式,給BookList寫注解即可

  在實體中,如果都不寫注解將都會顯示,如果有寫注解的,那么將只會顯示寫了注解的,其他的將不會顯示.

  在轉換成XML時,推薦使用simple和SAX,而Document限於理解XML解析原理,(simple和SAX的容錯效果更好),推薦使用

 

常見的兩種數據傳輸的格式:XML和JSON,但是JSON更簡單一些;可以看上一篇博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM