栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java操作xml的方法汇总及解析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java操作xml的方法汇总及解析

这篇文章主要介绍了java操作xml的方法汇总及解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一丶常用方法

主要有3个方面, 1读取xml文件, 2使用xpath根据指定路径获取某一节点数据 3, xml和java bean的转换

XmlUtils.java


public class XmlUtils {
  // --------------------------------------
  public static document createXml(){
    return XmlUtil.createXml();
  }

  // --------------------------------------
  
  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
  }
  // --------------------------------------

  // 根据路径获取某一节点

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

  
  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);
    }
  }
  // --------------------------------------
  // 转成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);
  }
  
  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转换
  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 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);
  }
}

二丶测试

@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
  
  @Test
  public void evalNodeTest(){
    BufferedInputStream bis=FileUtil.getInputStream("xml/bookstore.xml");
    document document=XmlUtils.readXml(bis);
    XPath xpath=XmlUtils.newXpath();
    // 1. 使用xpath表达式读取根节点
    Node rootNode=XmlUtils.evalNode("/bookstore", document, xpath);
    Assert.assertEquals("bookstore", rootNode.getNodeName());
    // 2. 使用xpath表达式读取nodeList
    NodeList bookNodeList =XmlUtils.evalNodeList("/bookstore/book", document, xpath);
    Node bookNode=null;
    for(int i=0; i 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"));

  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/136433.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号