<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                XML和JSON是兩種常用的數據交換格式。雖然對于XML和JSON的各種操作,僅僅是常用的工具jar包的使用,沒有什么技術含量,但鑒于這兩種數據格式的普遍使用,還是拿出一點時間,進行一下簡單總結。 # XML XML官網:[http://www.xml.com/](http://www.xml.com/) XML保留字符有5個:&、>、<、'、""。 對于XML的解析方式,有兩種:DOM方式和SAX方式。DOM是讀入內存之后進行各種操作,SAX是流式操作、一次性的。其他的一些工具jar包,比如JDOM、DOM4J,都是對于這兩種方式的高層次封裝。 **參考網址:** [http://wenku.baidu.com/link?url=7VjI_4xMpWdV2O82WrNI2KO2UNuhefJYeGYe17QUmH89Nlc9NH20oVr8ZMJ2w1RSvphm5UE88L4FhB4fJgCcV4HldRlJsP9n_o1n1r7gunG](http://wenku.baidu.com/link?url=7VjI_4xMpWdV2O82WrNI2KO2UNuhefJYeGYe17QUmH89Nlc9NH20oVr8ZMJ2w1RSvphm5UE88L4FhB4fJgCcV4HldRlJsP9n_o1n1r7gunG) [http://inotgaoshou.iteye.com/blog/1012188](http://inotgaoshou.iteye.com/blog/1012188) **DOM圖示:** ![](https://box.kancloud.cn/2016-05-27_5747b45086c6f.jpg) **SAX圖示:** ![](https://box.kancloud.cn/2016-05-27_5747b450a3889.jpg) **演示代碼:** ~~~ import java.io.File; import java.util.Stack; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * 演示兩種XML的解析方式:DOM和SAX * * 至于JDOM和DOM4J,只是在這兩種方式之上的更高層次的封裝 * */ public class XmlDemo { public static void main(String[] args) throws Exception { XmlDemo xmlDemo = new XmlDemo(); // DOM方式 DomDemo domDemo = xmlDemo.new DomDemo("src/main/java/com/cl/roadshow/java/xml/people.xml"); domDemo.iterateByName("PERSON"); domDemo.recursiveElement(); // SAX方式 SaxDemo saxDemo = xmlDemo.new SaxDemo("src/main/java/com/cl/roadshow/java/xml/people.xml"); saxDemo.showEvents(); saxDemo.parseDocument(); } /** * DOM方式解析XML * */ class DomDemo { private String path; public DomDemo(String path) { this.path = path; } /** * 查詢所有符合給到名稱的Node,大小寫敏感 * * @param tagName * @throws Exception */ public void iterateByName(String tagName) throws Exception { // 獲得DOM解析器工廠 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // 獲得具體的DOM解析器 DocumentBuilder db = dbf.newDocumentBuilder(); // 解析XML文檔,獲得Document對象(根結點) Document doc = db.parse(new File(path)); NodeList nodeList = doc.getElementsByTagName(tagName); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); String content = element.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue(); System.out.println("name:" + content); content = element.getElementsByTagName("ADDRESS").item(0).getFirstChild().getNodeValue(); System.out.println("address:" + content); content = element.getElementsByTagName("TEL").item(0).getFirstChild().getNodeValue(); System.out.println("tel:" + content); content = element.getElementsByTagName("FAX").item(0).getFirstChild().getNodeValue(); System.out.println("fax:" + content); content = element.getElementsByTagName("EMAIL").item(0).getFirstChild().getNodeValue(); System.out.println("email:" + content); System.out.println("--------------------------------------"); } } /** * 從根節點開始,遍歷XML的所有元素 * * @throws Exception */ public void recursiveElement() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File(path)); // 獲得根元素結點 Element root = doc.getDocumentElement(); parseElement(root); } /** * 遞歸方法 * * @param element */ private void parseElement(Element element) { String tagName = element.getNodeName(); NodeList children = element.getChildNodes(); System.out.print("<" + tagName); // element元素的所有屬性所構成的NamedNodeMap對象,需要對其進行判斷 NamedNodeMap map = element.getAttributes(); // 如果該元素存在屬性 if (null != map) { for (int i = 0; i < map.getLength(); i++) { // 獲得該元素的每一個屬性 Attr attr = (Attr) map.item(i); String attrName = attr.getName(); String attrValue = attr.getValue(); System.out.print(" " + attrName + "=\"" + attrValue + "\""); } } System.out.print(">"); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); // 獲得結點的類型 short nodeType = node.getNodeType(); if (nodeType == Node.ELEMENT_NODE) { // 是元素,繼續遞歸 parseElement((Element) node); } else if (nodeType == Node.TEXT_NODE) { // 遞歸出口 System.out.print(node.getNodeValue()); } else if (nodeType == Node.COMMENT_NODE) { System.out.print("<!--"); Comment comment = (Comment) node; // 注釋內容 String data = comment.getData(); System.out.print(data); System.out.print("-->"); } } System.out.print("</" + tagName + ">"); } } /** * SAX方式解析XML * */ class SaxDemo { private String path; public SaxDemo(String path) { this.path = path; } public void showEvents() throws Exception { // 獲得SAX解析器工廠實例 SAXParserFactory factory = SAXParserFactory.newInstance(); // 獲得SAX解析器實例 SAXParser parser = factory.newSAXParser(); // 開始進行解析 parser.parse(new File(path), new EventHandler()); } public void parseDocument() throws Exception { // 獲得SAX解析器工廠實例 SAXParserFactory factory = SAXParserFactory.newInstance(); // 獲得SAX解析器實例 SAXParser parser = factory.newSAXParser(); // 開始進行解析 parser.parse(new File(path), new ParseHandler()); } /** * 演示SAX解析方式的事件驅動過程 * */ class EventHandler extends DefaultHandler { @Override public void startDocument() throws SAXException { System.out.println("\n--------------------------------------"); System.out.println("start document"); } @Override public void endDocument() throws SAXException { System.out.println("finish document"); System.out.println("--------------------------------------"); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println("start element"); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { System.out.println("finish element"); } } /** * 演示用SAX方式解析PERSON節點的過程 * */ class ParseHandler extends DefaultHandler { private Stack<String> stack = new Stack<String>(); private String name; private String tel; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { stack.push(qName); for (int i = 0; i < attributes.getLength(); i++) { String attrName = attributes.getQName(i); String attrValue = attributes.getValue(i); System.out.println(attrName + "=" + attrValue); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { String tag = stack.peek(); if ("NAME".equals(tag)) { name = new String(ch, start, length); } else if ("TEL".equals(tag)) { tel = new String(ch, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { stack.pop(); // 表示該元素已經解析完畢,需要從棧中彈出 if ("PERSON".equals(qName)) { System.out.println("NAME:" + name); System.out.println("TEL:" + tel); System.out.println(); } } } } } ~~~ # JSON JSON官網:[http://www.json.org/json-zh.html](http://www.json.org/json-zh.html) 對于JSON的解析,各種語言下都有 很多可用客戶端,在Java下,fastjson是推薦使用的一種,快、強大、無依賴。 **代碼演示:** ~~~ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; /** * fastjson 是一個性能很好的 Java 語言實現的 JSON 解析器和生成器,來自阿里巴巴的工程師開發 * * * 主要特點:比其它任何基于Java的解析器和生成器更快,包括jackson;強大;零依賴 * */ public class FastjsonDemo { public static void main(String[] args) { // 將JSON和JavaBean對象互相轉換 Person person = new Person(1, "張三", null); String jsonString = JSON.toJSONString(person); System.out.println(jsonString); person = JSON.parseObject(jsonString, Person.class); System.out.println(person.getName()); System.out.println("--------------------------------------"); // 將JSON字符串轉化成List<JavaBean>對象 Person person1 = new Person(1, "fastjson1", 11); Person person2 = new Person(2, "fastjson2", 22); List<Person> persons = new ArrayList<Person>(); persons.add(person1); persons.add(person2); jsonString = JSON.toJSONString(persons); System.out.println("json字符串:" + jsonString); persons = JSON.parseArray(jsonString, Person.class); System.out.println(persons.toString()); System.out.println("--------------------------------------"); // 將JSON字符串轉化成List<String>對象 List<String> list1 = new ArrayList<String>(); list1.add("fastjson1"); list1.add("fastjson2"); list1.add("fastjson3"); jsonString = JSON.toJSONString(list1); System.out.println(jsonString); List<String> list2 = JSON.parseObject(jsonString, new TypeReference<List<String>>() { }); System.out.println("list2:" + list2.toString()); System.out.println("--------------------------------------"); // JSON<Map<String,Object>>對象 Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "value1"); map.put("key2", "value2"); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("key1", 1); map2.put("key2", 2); List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>(); list3.add(map); list3.add(map2); jsonString = JSON.toJSONString(list3); System.out.println("json字符串:" + jsonString); List<Map<String, Object>> list4 = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() { }); System.out.println("list4:" + list4.toString()); } } class Person { private Integer id; private String name; private Integer age; public Person() { } public Person(Integer id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ID:").append(id); sb.append("-Name:").append(name); sb.append("-Age:").append(age); return sb.toString(); } } ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看