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更简单一些;可以看上一篇博客

posted @ 2019-01-13 20:56  Bug研发工程师  阅读(1864)  评论(0编辑  收藏  举报