Operation and java xml json
1. XML
1.1 XML Introduction
The XML, Extensible Markup Language (extensible markup language), is a data representation format, it may defy very copied data structure for transmission and storage of data
Features:
- Plain text, UTF-8 encoding default
- Nestable, for showing the structure of the data
- General form of a document, such as: book.xml
1.2 Judgment
java parsing XML:
- Document: representative of the XML document
- Element: element
- Attribute: Attribute
- Text: text
- Comment: Comment
Java Dom core API:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("/Users/lingjing/IdeaProjects/hadooptest/pom.xml");
Element root = doc.getDocumentElement();
Java DOM API:
- Parse the XML into DOM
- Identification can complete XML data structure in memory
- Parsing slow, large memory footprint
Dom example
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class DOMTest {
static final String XML_URL = "http://rss.sina.com.cn/tech/internet/home28.xml";
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("/Users/lingjing/IdeaProjects/hadooptest/pom.xml");
printNode(doc, 0);
}
static void printNode(Node n, int indent) {
String tab = "";
for (int i = 0; i < indent; i++) {
// System.out.print(' ');
tab += "\t";
}
System.out.print(tab);
switch (n.getNodeType()) {
case Node.DOCUMENT_NODE:
System.out.println("Document: " + n.getNodeName());
break;
case Node.ELEMENT_NODE:
System.out.println("Element: " + n.getNodeName());
break;
case Node.TEXT_NODE:
System.out.println("Text: " + n.getNodeName() + " = " + n.getNodeValue());
break;
case Node.ATTRIBUTE_NODE:
System.out.println("Attr: " + n.getNodeName() + " = " + n.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
System.out.println("CDATA: " + n.getNodeName() + " = " + n.getNodeValue());
break;
case Node.COMMENT_NODE:
System.out.println("Comment: " + n.getNodeName() + " = " + n.getNodeValue());
break;
default:
System.out.println("NodeType: " + n.getNodeType() + ", NodeName: " + n.getNodeName());
}
for (Node child = n.getFirstChild(); child != null; child = child.getNextSibling()) {
printNode(child, indent + 1);
}
}
}
1.3 SAX
SAX: Simple Api for XML, event-based API
SAX parsing will trigger a series of events:
- starting document
- startElement
- Characters: Text
- endElement
- endDocument
SAX parsing XML:
- A streaming type of parsing XML API
- Triggered by events, fast
- Caller to get the data through a callback method
SAX Example:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class SAXSample {
static final String XML_URL = "http://rss.sina.com.cn/tech/internet/home28.xml";
public static void main(String[] args) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
saxParser.parse("/Users/lingjing/IdeaProjects/hadooptest/pom.xml", new MyHandler());
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
void print(Object... objs) {
for (Object obj : objs) {
System.out.print(obj);
System.out.print(" ");
}
System.out.println();
}
@Override
public void startDocument() throws SAXException {
print("start document");
}
@Override
public void endDocument() throws SAXException {
print("end document");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
print("start element:", localName, qName);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
print("end element:", localName, qName);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
print("characters:", new String(ch, start, length));
}
@Override
public void error(SAXParseException e) throws SAXException {
print("error:", e);
}
}
1.4 Jackson
Use Jackson:
- Open source tool to read and write XML
- Can conversion between XML and JavaBean
- Simple API interface
- Customizable Serialization
maven rely Address:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
Read XML: xml become the java object
XmlMapper mapper = new XmlMapper();
Book book = mapper.readValue(xml, Book.class);
Write XML: java object becomes the xml file and returns a string
XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(book);
2. fastjson
Configuring maven
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
Test the code:
import lombok.Data;
@Data
public class User {
private String name;
private int age;
}
public class TestUser {
public static void main(String[] args) {
User user = new User();
user.setAge(20);
user.setName("ajing");
// 把User对象变成json字符串
String jstr = JSON.toJSONString(user);
System.out.println(jstr);
// 把字符串变成User对象
User u1 = JSON.parseObject(jstr, User.class);
System.out.println(u1 instanceof User);
System.out.println(u1.getAge());
System.out.println(u1.getName());
}
}