有关W3C Document操作的XML工具类

简介:

    纯干货,你懂的,各位看官直接看代码:

Java代码   收藏代码
  1. package com.yida.spider4j.crawler.utils.xml;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.StringReader;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import javax.xml.parsers.DocumentBuilder;  
  11. import javax.xml.parsers.DocumentBuilderFactory;  
  12. import javax.xml.parsers.ParserConfigurationException;  
  13. import javax.xml.xpath.XPath;  
  14. import javax.xml.xpath.XPathConstants;  
  15. import javax.xml.xpath.XPathExpression;  
  16. import javax.xml.xpath.XPathExpressionException;  
  17. import javax.xml.xpath.XPathFactory;  
  18.   
  19. import org.w3c.dom.Document;  
  20. import org.w3c.dom.Node;  
  21. import org.w3c.dom.NodeList;  
  22. import org.xml.sax.InputSource;  
  23. import org.xml.sax.SAXException;  
  24.   
  25. import com.yida.spider4j.crawler.utils.common.GerneralUtils;  
  26.   
  27. /** 
  28.  * XML常用操作工具类 
  29.  *  
  30.  * @since 1.0 
  31.  * @author Lanxiaowei@citic-finance.com 
  32.  * @date 2015-6-16下午3:39:10 
  33.  *  
  34.  */  
  35. public class XMLUtils {  
  36.     private DocumentBuilder builder;  
  37.   
  38.     private XPath xpath;  
  39.       
  40.     private XMLUtils () {  
  41.         init();  
  42.     }  
  43.       
  44.     private static class SingletonHolder {    
  45.         private static final XMLUtils INSTANCE = new XMLUtils();    
  46.     }    
  47.   
  48.     public static final XMLUtils getInstance() {    
  49.         return SingletonHolder.INSTANCE;   
  50.     }    
  51.   
  52.     private void init() {  
  53.         if(builder == null) {  
  54.             DocumentBuilderFactory domfactory = DocumentBuilderFactory  
  55.                     .newInstance();  
  56.             domfactory.setValidating(false);  
  57.             domfactory.setIgnoringComments(true);  
  58.             try {  
  59.                 builder = domfactory.newDocumentBuilder();  
  60.             } catch (ParserConfigurationException e) {  
  61.                 throw new RuntimeException(  
  62.                         "Create DocumentBuilder instance occur one exception.");  
  63.             }  
  64.         }  
  65.           
  66.         if(xpath == null) {  
  67.             XPathFactory xpfactory = XPathFactory.newInstance();  
  68.             xpath = xpfactory.newXPath();  
  69.         }  
  70.     }  
  71.   
  72.        /** 
  73.      * @Author: Lanxiaowei(736031305@qq.com) 
  74.      * @Title: document2String 
  75.      * @Description: W3C Document对象转成XML String 
  76.      * @param @param doc 
  77.      * @param @return 
  78.      * @return String 
  79.      * @throws 
  80.      */  
  81.     public String document2String(Document doc) {  
  82.         DOMSource domSource = new DOMSource(doc);  
  83.         StringWriter writer = new StringWriter();  
  84.         StreamResult result = new StreamResult(writer);  
  85.         TransformerFactory tf = TransformerFactory.newInstance();  
  86.         Transformer transformer;  
  87.         try {  
  88.             transformer = tf.newTransformer();  
  89.             transformer.transform(domSource, result);  
  90.         } catch (TransformerException e) {  
  91.             throw new RuntimeException(  
  92.                 "Transformer org.w3c.dom.document object occur one exception.");  
  93.         }  
  94.         return writer.toString();  
  95.     }  
  96.   
  97.     /** 
  98.      * @Author Lanxiaowei 
  99.      * @Title: parseDocument 
  100.      * @Description: 根据XML路径解析XML文档 
  101.      * @param path 
  102.      * @return 
  103.      * @return Document 
  104.      * @throws 
  105.      */  
  106.     public Document parseDocument(String path) {  
  107.         try {  
  108.             return builder.parse(path);  
  109.         } catch (SAXException e) {  
  110.             throw new RuntimeException(  
  111.                     "The xml path is invalid or parsing xml occur exception.");  
  112.         } catch (IOException e) {  
  113.             throw new RuntimeException(  
  114.                     "The xml path is invalid or parsing xml occur exception.");  
  115.         }  
  116.     }  
  117.   
  118.     /** 
  119.      * @Author Lanxiaowei 
  120.      * @Title: parseDocument 
  121.      * @Description: 根据文件解析XML文档 
  122.      * @param file 
  123.      * @return 
  124.      * @return Document 
  125.      * @throws 
  126.      */  
  127.     public Document parseDocument(File file) {  
  128.         try {  
  129.             return builder.parse(file);  
  130.         } catch (SAXException e) {  
  131.             throw new RuntimeException(  
  132.                     "The input xml file is null or parsing xml occur exception.");  
  133.         } catch (IOException e) {  
  134.             throw new RuntimeException(  
  135.                     "The input xml file is null or parsing xml occur exception.");  
  136.         }  
  137.   
  138.     }  
  139.   
  140.     /** 
  141.      * @Author Lanxiaowei 
  142.      * @Title: parseDocument 
  143.      * @Description: 根据输入流解析XML文档 
  144.      * @param is 
  145.      * @return 
  146.      * @throws IOException 
  147.      * @throws SAXException 
  148.      * @return Document 
  149.      * @throws 
  150.      */  
  151.     public Document parseDocument(InputStream is) {  
  152.         try {  
  153.             return builder.parse(is);  
  154.         } catch (SAXException e) {  
  155.             throw new RuntimeException(  
  156.                     "The input xml fileInputStream is null or parsing xml occur exception.");  
  157.         } catch (IOException e) {  
  158.             throw new RuntimeException(  
  159.                     "The input xml fileInputStream is null or parsing xml occur exception.");  
  160.         }  
  161.     }  
  162.   
  163.     /** 
  164.      * @Author: Lanxiaowei(736031305@qq.com) 
  165.      * @Title: fragment2Document 
  166.      * @Description: 将html代码片段转换成document对象 
  167.      * @param @param fragment 
  168.      * @param @return 
  169.      * @return Document 
  170.      * @throws 
  171.      */  
  172.     public Document fragment2Document(String fragment) {  
  173.         try {  
  174.             return builder.parse(new InputSource(new StringReader(fragment)));  
  175.         } catch (SAXException e) {  
  176.             throw new RuntimeException(  
  177.                     "parse fragment to document occur SAXException,please check your fragment.");  
  178.         } catch (IOException e) {  
  179.             throw new RuntimeException(  
  180.                     "parse fragment to document occur one IOException.");  
  181.         }  
  182.     }  
  183.   
  184.     /** 
  185.      * @Author Lanxiaowei 
  186.      * @Title: selectNodes 
  187.      * @Description: 通过xpath获取节点列表 
  188.      * @param node 
  189.      * @param expression 
  190.      * @return 
  191.      * @throws XPathExpressionException 
  192.      * @return NodeList 
  193.      * @throws 
  194.      */  
  195.     public NodeList selectNodes(Node node, String expression) {  
  196.         XPathExpression xpexpreesion = null;  
  197.         try {  
  198.             xpexpreesion = this.xpath.compile(expression);  
  199.             return (NodeList) xpexpreesion.evaluate(node,  
  200.                     XPathConstants.NODESET);  
  201.         } catch (XPathExpressionException e) {  
  202.             throw new RuntimeException(  
  203.                     "Compile xpath expression occur excetion,please check out your xpath expression.");  
  204.         }  
  205.     }  
  206.   
  207.     /** 
  208.      * @Author Lanxiaowei 
  209.      * @Title: selectSingleNode 
  210.      * @Description: 通过xpath获取单个节点 
  211.      * @param node 
  212.      * @param expression 
  213.      * @return 
  214.      * @return Node 
  215.      * @throws 
  216.      */  
  217.     public Node selectSingleNode(Node node, String expression) {  
  218.         XPathExpression xpexpreesion = null;  
  219.         try {  
  220.             xpexpreesion = this.xpath.compile(expression);  
  221.             return (Node) xpexpreesion.evaluate(node, XPathConstants.NODE);  
  222.         } catch (XPathExpressionException e) {  
  223.             throw new RuntimeException(  
  224.                     "Compile xpath expression occur excetion,please check out your xpath expression.");  
  225.         }  
  226.     }  
  227.   
  228.     /** 
  229.      * @Author Lanxiaowei 
  230.      * @Title: getNodeText 
  231.      * @Description: 根据xpath获取节点的文本值(只返回匹配的第一个节点的文本值) 
  232.      * @param node 
  233.      * @param expression 
  234.      * @return 
  235.      * @return String 
  236.      * @throws 
  237.      */  
  238.     public String getNodeText(Node node, String expression) {  
  239.         XPathExpression xpexpreesion = null;  
  240.         try {  
  241.             xpexpreesion = this.xpath.compile(expression);  
  242.             return (String) xpexpreesion.evaluate(node, XPathConstants.STRING);  
  243.         } catch (XPathExpressionException e) {  
  244.             throw new RuntimeException(  
  245.                     "Compile xpath expression occur excetion,please check out your xpath expression.");  
  246.         }  
  247.     }  
  248.       
  249.     /** 
  250.      * @Author: Lanxiaowei(736031305@qq.com) 
  251.      * @Title: getMultiNodeText 
  252.      * @Description: 根据xpath获取节点的文本值(若xpath表达式匹配到多个节点,则会提取所有匹配到节点的文本值) 
  253.      * @param @param node 
  254.      * @param @param expression 
  255.      * @param @return 
  256.      * @return List<String> 
  257.      * @throws 
  258.      */  
  259.     public List<String> getMultiNodeText(Node node, String expression) {  
  260.         NodeList nodeList = selectNodes(node, expression);  
  261.         if(null == nodeList || nodeList.getLength() == 0) {  
  262.             return null;  
  263.         }  
  264.         List<String> list = new ArrayList<String>();  
  265.         for(int i=0; i < nodeList.getLength(); i++) {  
  266.             Node n = nodeList.item(i);  
  267.             String text = n.getTextContent();  
  268.             list.add(text);  
  269.         }  
  270.         return list;  
  271.     }  
  272.       
  273.        /** 
  274.      * @Author: Lanxiaowei(736031305@qq.com) 
  275.      * @Title: getNodeAttributeValue 
  276.      * @Description: 根据xpath获取节点的属性值(若xpath表达式匹配到多个节点,则只会提取匹配到的第一个节点的属性值) 
  277.      * @param @param node 
  278.      * @param @param expression 
  279.      * @param @param atrributeName 
  280.      * @param @return 
  281.      * @return String 
  282.      * @throws 
  283.      */  
  284.     public String getNodeAttributeValue(Node node,  
  285.             String expression, String atrributeName) {  
  286.         Node matchNode = selectSingleNode(node, expression);  
  287.         if (null == matchNode) {  
  288.             return null;  
  289.         }  
  290.         Node attNode = matchNode.getAttributes().getNamedItem(  
  291.                 atrributeName);  
  292.         if (null == attNode) {  
  293.             return null;  
  294.         }  
  295.         return attNode.getNodeValue();  
  296.     }  
  297.     /** 
  298.      * @Author: Lanxiaowei(736031305@qq.com) 
  299.      * @Title: getMultiNodeAttributeValue 
  300.      * @Description: 根据xpath获取节点的属性值(若xpath表达式匹配到多个节点,则会提取所有匹配到节点的属性值) 
  301.      * @param @param node 
  302.      * @param @param expression      Xpath表达式,如div\span[@class] 
  303.      * @param @param atrributeName   属性名称 
  304.      * @param @return 
  305.      * @return List<String> 
  306.      * @throws 
  307.      */  
  308.     public List<String> getMultiNodeAttributeValue(Node node, String expression,String atrributeName) {  
  309.         NodeList nodeList = selectNodes(node, expression);  
  310.         if(null == nodeList || nodeList.getLength() == 0) {  
  311.             return null;  
  312.         }  
  313.         List<String> list = new ArrayList<String>();  
  314.         for(int i=0; i < nodeList.getLength(); i++) {  
  315.             Node currentItem = nodeList.item(i);  
  316.             Node attNode = currentItem.getAttributes().getNamedItem(atrributeName);  
  317.             if(null == attNode) {  
  318.                 continue;  
  319.             }  
  320.             String val = currentItem.getAttributes().getNamedItem(atrributeName).getNodeValue();  
  321.             list.add(val);  
  322.         }  
  323.         return list;  
  324.     }  
  325.   
  326.     public static void main(String[] args) throws ParserConfigurationException,  
  327.             SAXException, IOException {  
  328.   
  329.         /*String fragment = "<data><employee><name>益达</name>" 
  330.                 + "<title>Manager</title></employee></data>"; 
  331.  
  332.         XMLUtils util = new XMLUtils(); 
  333.         Document doc = util.fragment2Document(fragment); 
  334.         NodeList nodes = doc.getElementsByTagName("employee"); 
  335.  
  336.         for (int i = 0; i < nodes.getLength(); i++) { 
  337.             Element element = (Element) nodes.item(i); 
  338.  
  339.             NodeList name = element.getElementsByTagName("name"); 
  340.             Element line = (Element) name.item(0); 
  341.             System.out.println("Name: " + line.getNodeName() + ":" 
  342.                     + line.getTextContent()); 
  343.  
  344.             NodeList title = element.getElementsByTagName("title"); 
  345.             line = (Element) title.item(0); 
  346.             System.out.println("Name: " + line.getNodeName() + ":" 
  347.                     + line.getTextContent()); 
  348.         }*/  
  349.           
  350.         String fragment = "<data><employee><name id=\"1\">益达</name><name id=\"2\">yida</name>"  
  351.                 + "<title>Manager</title></employee></data>";  
  352.   
  353.         XMLUtils util = new XMLUtils();  
  354.         Document doc = util.fragment2Document(fragment);  
  355.           
  356.           
  357.         List<String> strList = util.getMultiNodeText(doc, "//employee/name[@id]");  
  358.         String s = GerneralUtils.joinCollection(strList);  
  359.         System.out.println(s);  
  360.           
  361.         strList = util.getMultiNodeAttributeValue(doc, "//employee/name[@id]""id");  
  362.         s = GerneralUtils.joinCollection(strList);  
  363.         System.out.println(s);  
  364.     }  
  365. }  

 

    注意这里说的Document指的都是org.w3c.dom.Document,而不是JDOM or DOM4J or Jsoup里的Document.org.w3c.dom.Document是JDK原生对象.

转载:http://iamyida.iteye.com/blog/2247529

目录
相关文章
|
4月前
|
XML C# 数据格式
使用C#操作XML文件
使用C#操作XML文件
|
4月前
|
XML Java 开发工具
jdom操作xml实战
jdom操作xml实战
|
3月前
|
XML Java 数据格式
Spring5系列学习文章分享---第一篇(概述+特点+IOC原理+IOC并操作之bean的XML管理操作)
Spring5系列学习文章分享---第一篇(概述+特点+IOC原理+IOC并操作之bean的XML管理操作)
37 1
|
3月前
|
XML 数据格式
Xml declaration should precede all document content
Xml declaration should precede all document content
|
11月前
|
XML Android开发 数据格式
IOException parsing XML document from class path resource [applicationContext.xml];
IOException parsing XML document from class path resource [applicationContext.xml];
|
4月前
|
XML Java 数据格式
java使用Document类解析xml并创建子标签节点
java使用Document类解析xml并创建子标签节点
|
4月前
|
XML 存储 JavaScript
深入学习 XML 解析器及 DOM 操作技术
所有主要的浏览器都内置了一个XML解析器,用于访问和操作XML XML 解析器 在访问XML文档之前,必须将其加载到XML DOM对象中 所有现代浏览器都有一个内置的XML解析器,可以将文本转换为XML DOM对象
109 0
|
4月前
|
XML Java 数据库连接
Mybatis之简介、使用操作(安装、XML、SqlSession、映射的SQL语句、命名空间、作用域和生命周期)
【1月更文挑战第2天】 MyBatis 是一款优秀的持久层框架 MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程 MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
147 2
Mybatis之简介、使用操作(安装、XML、SqlSession、映射的SQL语句、命名空间、作用域和生命周期)
|
XML Java 数据库连接
java202304java学习笔记第六十五天-ssm-声明式控制-基于xml的声明式配置-原始jdbc操作1
java202304java学习笔记第六十五天-ssm-声明式控制-基于xml的声明式配置-原始jdbc操作1
56 0
|
4月前
|
XML JavaScript Java
Spring5源码(16)-Spring将Xml文件解析为Document对象
Spring5源码(16)-Spring将Xml文件解析为Document对象
58 0