本篇文章為大家展示了如何在java中操作xml,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
成都創(chuàng)新互聯(lián)公司執(zhí)著的堅(jiān)持網(wǎng)站建設(shè),微信小程序定制開發(fā);我們不會(huì)轉(zhuǎn)行,已經(jīng)持續(xù)穩(wěn)定運(yùn)營(yíng)10年。專業(yè)的技術(shù),豐富的成功經(jīng)驗(yàn)和創(chuàng)作思維,提供一站式互聯(lián)網(wǎng)解決方案,以客戶的口碑塑造品牌,攜手廣大客戶,共同發(fā)展進(jìn)步。
一丶常用方法
主要有3個(gè)方面, 1讀取xml文件, 2使用xpath根據(jù)指定路徑獲取某一節(jié)點(diǎn)數(shù)據(jù) 3, xml和java bean的轉(zhuǎn)換
XmlUtils.java
public class XmlUtils { // -------------------------------------- public static Document createXml(){ return XmlUtil.createXml(); } // -------------------------------------- /** * 讀取xml文檔 * @param xmlInputStream * @return */ public static Document readXml(InputStream xmlInputStream){ return readXml(xmlInputStream, false); } public static Document readXml(InputStream xmlInputStream, boolean validate){ // 參考mybatis parsing模塊 try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(validate); factory.setNamespaceAware(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(false); factory.setCoalescing(false); factory.setExpandEntityReferences(true); DocumentBuilder builder=factory.newDocumentBuilder(); return builder.parse(xmlInputStream); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } public static Document readXml(String xmlStr){ return XmlUtil.parseXml(xmlStr); //使用hutool } // -------------------------------------- // 根據(jù)路徑獲取某一節(jié)點(diǎn) public static XPath newXpath(){ return XPathFactory.newInstance().newXPath(); } /** * 根據(jù)路徑獲取某一節(jié)點(diǎn), 語(yǔ)法看 https://www.w3school.com.cn/xpath/xpath_syntax.asp * @param expression * @param root 可以是document, 可以是Node等其他節(jié)點(diǎn) * @param xpath * @return 返回的節(jié)點(diǎn)可以修改 */ public static Node evalNode(String expression, Object root, XPath xpath){ return (Node)evaluate(expression, root, XPathConstants.NODE, xpath); } public static NodeList evalNodeList(String expression, Object root, XPath xpath){ return (NodeList)evaluate(expression, root, XPathConstants.NODESET, xpath); } public static Double evalDouble(String expression, Object root, XPath xpath) { return (Double) evaluate(expression, root, XPathConstants.NUMBER, xpath); } public static Boolean evalBoolean(String expression, Object root, XPath xpath) { return (Boolean) evaluate(expression, root, XPathConstants.BOOLEAN, xpath); } public static String evalString(String expression, Object root, XPath xpath) { return (String) evaluate(expression, root, XPathConstants.STRING, xpath); } public static Long evalLong(String expression, Object root, XPath xpath){ return Long.valueOf(evalString(expression, root, xpath)); } public static Integer evalInteger(String expression, Object root, XPath xpath){ return Integer.valueOf(evalString(expression, root, xpath)); } public static Float evalFloat(String expression, Object root, XPath xpath){ return Float.valueOf(evalString(expression, root, xpath)); } public static Short evalShort(String expression, Object root, XPath xpath){ return Short.valueOf(evalString(expression, root, xpath)); } private static Object evaluate(String expression, Object root, QName returnType, XPath xpath) { try { return xpath.evaluate(expression, root, returnType); } catch (Exception e) { throw new RuntimeException("Error evaluating XPath. Cause: " + e, e); } } // -------------------------------------- // 轉(zhuǎn)成string public static String toStr(Node node){ return toStr(node, false); } public static String toStr(Node node, boolean isPretty){ return toStr(node, "utf-8", isPretty); } /** * * @param node * @param charset 編碼 * @param isPretty 是否格式化輸出 * @return */ public static String toStr(Node node, String charset, boolean isPretty){ final StringWriter writer = StrUtil.getWriter(); final int INDENT_DEFAULT=2; try { XmlUtil.transform(new DOMSource(node), new StreamResult(writer), charset, isPretty ? INDENT_DEFAULT : 0); } catch (Exception e) { throw new UtilException(e, "Trans xml document to string error!"); } return writer.toString(); } //---------------------------------------- // 和java bean轉(zhuǎn)換 public static JSONObject toJSONObject(String xmlStr){ return XML.toJSONObject(xmlStr); } public static JSONObject toJSONObject(Node node){ String xmlStr=toStr(node); return toJSONObject(xmlStr); } public staticT toBean(Node node, Class clazz){ return toJSONObject(node).toBean(clazz); } public static Node toNode(Object obj){ String xml=toXml(obj); Node rootNode=readXml(xml).getFirstChild(); return rootNode; } public static String toXml(Object obj){ return XML.toXml(obj); } }
二丶測(cè)試
@Test public void readXmlFromInputStreamTest(){ BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml"); Document document=XmlUtils.readXml(bis); String nodeName=document.getFirstChild().getNodeName(); System.out.println(nodeName); Assert.assertTrue(nodeName.equals("bookstore")); } @Test public void readXmlStringTest() throws IOException { BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml"); String xmlStr=StreamUtils.copyToString(bis, Charset.defaultCharset()); Document document=XmlUtils.readXml(xmlStr); String nodeName=document.getFirstChild().getNodeName(); System.out.println(nodeName); Assert.assertTrue(nodeName.equals("bookstore")); } // -------------------------------------------- xpath /* https://www.w3school.com.cn/xpath/xpath_syntax.asp nodename 選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn)。 / 從根節(jié)點(diǎn)選取。 // 從匹配選擇的當(dāng)前節(jié)點(diǎn)選擇文檔中的節(jié)點(diǎn),而不考慮它們的位置。 . 選取當(dāng)前節(jié)點(diǎn)。 .. 選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)。 @ 選取屬性。 */ @Test public void evalNodeTest(){ BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml"); Document document=XmlUtils.readXml(bis); XPath xpath=XmlUtils.newXpath(); // 1. 使用xpath表達(dá)式讀取根節(jié)點(diǎn) Node rootNode=XmlUtils.evalNode("/bookstore", document, xpath); Assert.assertEquals("bookstore", rootNode.getNodeName()); // 2. 使用xpath表達(dá)式讀取nodeList NodeList bookNodeList =XmlUtils.evalNodeList("/bookstore/book", document, xpath); Node bookNode=null; for(int i=0; ibookList=bookstore.getBook(); Book book1=bookList.get(0); Assert.assertTrue(book1.getTitle().getLang().equals("en")); Assert.assertTrue(book1.getTitle().getContent().equals("Harry Potter")); Assert.assertTrue(book1.getAuthor().equals("J K. Rowling")); Book book2=bookList.get(1); Assert.assertTrue(book2.getTitle().getLang().equals("cn")); Assert.assertTrue(book2.getTitle().getContent().equals("where I am from")); Assert.assertTrue(book2.getAuthor().equals("timfruit")); }
1.SpringMVC,Spring Web MVC是一種基于Java的實(shí)現(xiàn)了Web MVC設(shè)計(jì)模式的請(qǐng)求驅(qū)動(dòng)類型的輕量級(jí)Web框架。2.Shiro,Apache Shiro是Java的一個(gè)安全框架。3.Mybatis,MyBatis 是支持普通 SQL查詢,存儲(chǔ)過程和高級(jí)映射的優(yōu)秀持久層框架。4.Dubbo,Dubbo是一個(gè)分布式服務(wù)框架。5.Maven,Maven是個(gè)項(xiàng)目管理和構(gòu)建自動(dòng)化工具。6.RabbitMQ,RabbitMQ是用Erlang實(shí)現(xiàn)的一個(gè)高并發(fā)高可靠AMQP消息隊(duì)列服務(wù)器。7.Ehcache,EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架。
上述內(nèi)容就是如何在java中操作xml,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。