亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java操作xml的方法匯總及解析

 更新時間:2019年11月04日 09:05:10   作者:timfruit  
這篇文章主要介紹了java操作xml的方法匯總及解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

這篇文章主要介紹了java操作xml的方法匯總及解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

一丶常用方法

主要有3個方面, 1讀取xml文件, 2使用xpath根據(jù)指定路徑獲取某一節(jié)點數(shù)據(jù) 3, xml和java bean的轉(zhuǎn)換

XmlUtils.java

/**
 * 和cn.hutool.core.util.XmlUtil許多功能重合, 本類可以當(dāng)做學(xué)習(xí)的例子
 * 可以直接使用cn.hutool.core.util.XmlUtil
 *
 * @author TimFruit
 * @date 19-11-2 下午5:22
 */
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é)點

  public static XPath newXpath(){
    return XPathFactory.newInstance().newXPath();
  }

  /**
   * 根據(jù)路徑獲取某一節(jié)點, 語法看 https://www.w3school.com.cn/xpath/xpath_syntax.asp
   * @param expression
   * @param root 可以是document, 可以是Node等其他節(jié)點
   * @param xpath
   * @return 返回的節(jié)點可以修改
   */
  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 static <T> T toBean(Node node, Class<T> 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);
  }
}

二丶測試

@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é)點的所有子節(jié)點。
  /   從根節(jié)點選取。
  //   從匹配選擇的當(dāng)前節(jié)點選擇文檔中的節(jié)點,而不考慮它們的位置。
  .   選取當(dāng)前節(jié)點。
  ..   選取當(dāng)前節(jié)點的父節(jié)點。
  @   選取屬性。
   */
  @Test
  public void evalNodeTest(){
    BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml");
    Document document=XmlUtils.readXml(bis);
    XPath xpath=XmlUtils.newXpath();
    // 1. 使用xpath表達(dá)式讀取根節(jié)點
    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; i<bookNodeList.getLength(); i++){
      bookNode=bookNodeList.item(i);
      Assert.assertEquals("book", bookNode.getNodeName());
    }


    // 3. 使用xpath表達(dá)式從節(jié)點讀取nodeList
    bookNodeList=XmlUtils.evalNodeList("/book", rootNode, xpath);
    for(int i=0; i<bookNodeList.getLength(); i++){
      bookNode=bookNodeList.item(i);
      Assert.assertEquals("book", bookNode.getNodeName());
    }

    // 4. 使用xpath表達(dá)式讀取屬性 數(shù)組表達(dá)式從1開始, /@ 修飾獲取屬性
    String lang=XmlUtils.evalString("/bookstore/book[1]/title/@lang", document, xpath);
    Assert.assertEquals("en", lang);

    lang=XmlUtils.evalString("/bookstore/book[2]/title/@lang", document, xpath);
    Assert.assertEquals("cn", lang);
  }
  // --------------------------------- 轉(zhuǎn)換

  @Test
  public void xmlToJSONObjectTest() throws IOException {
    BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml");
    String xmlStr=StreamUtils.copyToString(bis, Charset.forName("utf-8"));
    JSONObject jso=XmlUtils.toJSONObject(xmlStr);
    Assert.assertTrue(jso.getJSONObject("bookstore")!=null);
    Assert.assertTrue(jso.getJSONObject("bookstore").getJSONArray("book")!=null);
  }
  @Test
  public void nodeToJSONObjectTest(){
    BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml");
    Document document=XmlUtils.readXml(bis);
    JSONObject jso=XmlUtils.toJSONObject(document);
    Assert.assertTrue(jso.getJSONObject("bookstore")!=null);
    Assert.assertTrue(jso.getJSONObject("bookstore").getJSONArray("book")!=null);
  }
  @Test
  public void toBeanTest(){
    BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml");
    Document document=XmlUtils.readXml(bis);
    XmlBookstoreDto dto=XmlUtils.toBean(document, XmlBookstoreDto.class);
    Bookstore bookstore=dto.getBookstore();
    Assert.assertNotNull(bookstore);
    List<Book> bookList=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"));

  }

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java的synchronized關(guān)鍵字深入解析

    Java的synchronized關(guān)鍵字深入解析

    這篇文章主要介紹了Java的synchronized關(guān)鍵字深入解析,在并發(fā)編程中,多線程同時并發(fā)訪問的資源叫做臨界資源,當(dāng)多個線程同時訪問對象并要求操作相同資源時,分割了原子操作就有可能出現(xiàn)數(shù)據(jù)的不一致或數(shù)據(jù)不完整的情況,需要的朋友可以參考下
    2023-12-12
  • Java使用Callable和Future創(chuàng)建線程操作示例

    Java使用Callable和Future創(chuàng)建線程操作示例

    這篇文章主要介紹了Java使用Callable和Future創(chuàng)建線程操作,結(jié)合實例形式分析了java使用Callable接口和Future類創(chuàng)建線程的相關(guān)操作技巧與注意事項,需要的朋友可以參考下
    2019-09-09
  • 新版idea創(chuàng)建spring boot項目的詳細(xì)教程

    新版idea創(chuàng)建spring boot項目的詳細(xì)教程

    這篇文章給大家介紹了新版idea創(chuàng)建spring boot項目的詳細(xì)教程,本教程對新手小白友好,若根據(jù)教程創(chuàng)建出現(xiàn)問題導(dǎo)致失敗可下載我提供的源碼,在文章最后,本教程較新,文中通過圖文給大家介紹的非常詳細(xì),感興趣的朋友可以參考下
    2024-01-01
  • spring控制事務(wù)的三種方式小結(jié)

    spring控制事務(wù)的三種方式小結(jié)

    這篇文章主要介紹了spring控制事務(wù)的三種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java面試必備之AQS阻塞隊列和條件隊列

    Java面試必備之AQS阻塞隊列和條件隊列

    我們大概知道AQS就是一個框架,把很多功能都給實現(xiàn)了(比如入隊規(guī)則,喚醒節(jié)點中的線程等),我們?nèi)绻褂玫脑捴恍枰獙崿F(xiàn)其中的一些方法(比如tryAcquire等)就行了!這次主要說說AQS中阻塞隊列的的入隊規(guī)則還有條件變量,需要的朋友可以參考下
    2021-06-06
  • Java中List轉(zhuǎn)字符串的5種方法解析

    Java中List轉(zhuǎn)字符串的5種方法解析

    在Java中將一個List轉(zhuǎn)換為字符串有多種方法,下面這篇文章主要給大家介紹了關(guān)于Java中List轉(zhuǎn)字符串的5種方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-11-11
  • 關(guān)于Assert.assertEquals報錯的問題及解決

    關(guān)于Assert.assertEquals報錯的問題及解決

    這篇文章主要介紹了關(guān)于Assert.assertEquals報錯的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • springBoot集成redis的key,value序列化的相關(guān)問題

    springBoot集成redis的key,value序列化的相關(guān)問題

    這篇文章主要介紹了springBoot集成redis的key,value序列化的相關(guān)問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • 簡單聊一聊Spring中Bean別名的處理原理

    簡單聊一聊Spring中Bean別名的處理原理

    今天來和小伙伴們聊一聊 Spring 中關(guān)于 Bean 別名的處理邏輯,別名,顧名思義就是給一個 Bean 去兩個甚至多個名字,整體上來說,在 Spring 中,有兩種不同的別名定義方式,感興趣的小伙伴跟著小編一起來看看吧
    2023-09-09
  • SpringBoot深入淺出分析初始化器

    SpringBoot深入淺出分析初始化器

    這篇文章主要介紹了SpringBoot初始化器的分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07

最新評論