有关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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将 `org.w3c.dom.Document` 转换成 `InputStream` 可以通过以下步骤实现: 1. 创建一个 `Transformer` 对象,用于将 `Document` 转换为 `StreamResult` 对象。 ``` TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); ``` 2. 创建一个 `ByteArrayOutputStream` 对象,用于将 `StreamResult` 对象转换为字节数组。 ``` ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(outputStream); ``` 3. 将 `Document` 转换为 `StreamResult` 对象。 ``` DOMSource source = new DOMSource(document); transformer.transform(source, result); ``` 4. 将字节数组转换为 `InputStream` 对象。 ``` InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ``` 完整代码: ``` TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(outputStream); DOMSource source = new DOMSource(document); transformer.transform(source, result); InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ``` ### 回答2: 要将org.w3c.dom.Document转换为InputStream,可以使用以下步骤: 首先,将Document转换为字符串。可以使用Transformer类将Document对象转换为字符串。示例如下: ``` TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); String xmlString = writer.getBuffer().toString(); ``` 然后,将字符串转换为InputStream。可以使用ByteArrayInputStream类将字符串转换为InputStream。示例如下: ``` InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes()); ``` 最后,您现在可以使用inputStream进行进一步的操作,例如将其传递给其他方法或用于输入到其他API中。 请注意,上述代码片段中的变量document是指org.w3c.dom.Document对象,您需要将其替换为实际的Document对象引用。另外,还需要处理Transformer类的一些异常,例如TransformerException等。该示例仅仅展示了转换的主要步骤,您可能需要根据具体的需求进行适当的错误处理和异常处理。 ### 回答3: 要将org.w3c.dom.Document转换为InputStream,可以使用Java中提供的工具类Document对象序列化为字节数组,然后再将字节数组封装为InputStream对象。 具体步骤如下: 1. 导入相关的Java类库: ```java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.w3c.dom.Document; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; ``` 2. 定义一个方法将Document对象转换为InputStream: ```java public static InputStream documentToInputStream(Document document) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError, IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(new DOMSource(document), new StreamResult(outputStream)); // 将字节数组转换为InputStream InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); return inputStream; } ``` 3. 调用上述方法将Document对象转换为InputStream: ```java Document document = ...; // 获取到一个org.w3c.dom.Document对象 try { InputStream inputStream = documentToInputStream(document); // 可以使用inputStream进行后续操作 } catch (TransformerConfigurationException | TransformerException | TransformerFactoryConfigurationError | IOException e) { e.printStackTrace(); } ``` 以上是将org.w3c.dom.Document转换为InputStream的方法,通过将Document对象序列化为字节数组后再封装为InputStream对象,实现了转换的过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值