有关W3C Document操作的XML工具类

2023-11-02 01:38
文章标签 工具 xml 操作 document w3c

本文主要是介绍有关W3C Document操作的XML工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

package com.yida.spider4j.crawler.utils.xml;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;import com.yida.spider4j.crawler.utils.common.GerneralUtils;/*** XML常用操作工具类* * @since 1.0* @author Lanxiaowei@citic-finance.com* @date 2015-6-16下午3:39:10* */
public class XMLUtils {private DocumentBuilder builder;private XPath xpath;private XMLUtils () {init();}private static class SingletonHolder {  private static final XMLUtils INSTANCE = new XMLUtils();  }  public static final XMLUtils getInstance() {  return SingletonHolder.INSTANCE; }  private void init() {if(builder == null) {DocumentBuilderFactory domfactory = DocumentBuilderFactory.newInstance();domfactory.setValidating(false);domfactory.setIgnoringComments(true);try {builder = domfactory.newDocumentBuilder();} catch (ParserConfigurationException e) {throw new RuntimeException("Create DocumentBuilder instance occur one exception.");}}if(xpath == null) {XPathFactory xpfactory = XPathFactory.newInstance();xpath = xpfactory.newXPath();}}/*** @Author: Lanxiaowei(736031305@qq.com)* @Title: document2String* @Description: W3C Document对象转成XML String* @param @param doc* @param @return* @return String* @throws*/public String document2String(Document doc) {DOMSource domSource = new DOMSource(doc);StringWriter writer = new StringWriter();StreamResult result = new StreamResult(writer);TransformerFactory tf = TransformerFactory.newInstance();Transformer transformer;try {transformer = tf.newTransformer();transformer.transform(domSource, result);} catch (TransformerException e) {throw new RuntimeException("Transformer org.w3c.dom.document object occur one exception.");}return writer.toString();}/*** @Author Lanxiaowei* @Title: parseDocument* @Description: 根据XML路径解析XML文档* @param path* @return* @return Document* @throws*/public Document parseDocument(String path) {try {return builder.parse(path);} catch (SAXException e) {throw new RuntimeException("The xml path is invalid or parsing xml occur exception.");} catch (IOException e) {throw new RuntimeException("The xml path is invalid or parsing xml occur exception.");}}/*** @Author Lanxiaowei* @Title: parseDocument* @Description: 根据文件解析XML文档* @param file* @return* @return Document* @throws*/public Document parseDocument(File file) {try {return builder.parse(file);} catch (SAXException e) {throw new RuntimeException("The input xml file is null or parsing xml occur exception.");} catch (IOException e) {throw new RuntimeException("The input xml file is null or parsing xml occur exception.");}}/*** @Author Lanxiaowei* @Title: parseDocument* @Description: 根据输入流解析XML文档* @param is* @return* @throws IOException* @throws SAXException* @return Document* @throws*/public Document parseDocument(InputStream is) {try {return builder.parse(is);} catch (SAXException e) {throw new RuntimeException("The input xml fileInputStream is null or parsing xml occur exception.");} catch (IOException e) {throw new RuntimeException("The input xml fileInputStream is null or parsing xml occur exception.");}}/*** @Author: Lanxiaowei(736031305@qq.com)* @Title: fragment2Document* @Description: 将html代码片段转换成document对象* @param @param fragment* @param @return* @return Document* @throws*/public Document fragment2Document(String fragment) {try {return builder.parse(new InputSource(new StringReader(fragment)));} catch (SAXException e) {throw new RuntimeException("parse fragment to document occur SAXException,please check your fragment.");} catch (IOException e) {throw new RuntimeException("parse fragment to document occur one IOException.");}}/*** @Author Lanxiaowei* @Title: selectNodes* @Description: 通过xpath获取节点列表* @param node* @param expression* @return* @throws XPathExpressionException* @return NodeList* @throws*/public NodeList selectNodes(Node node, String expression) {XPathExpression xpexpreesion = null;try {xpexpreesion = this.xpath.compile(expression);return (NodeList) xpexpreesion.evaluate(node,XPathConstants.NODESET);} catch (XPathExpressionException e) {throw new RuntimeException("Compile xpath expression occur excetion,please check out your xpath expression.");}}/*** @Author Lanxiaowei* @Title: selectSingleNode* @Description: 通过xpath获取单个节点* @param node* @param expression* @return* @return Node* @throws*/public Node selectSingleNode(Node node, String expression) {XPathExpression xpexpreesion = null;try {xpexpreesion = this.xpath.compile(expression);return (Node) xpexpreesion.evaluate(node, XPathConstants.NODE);} catch (XPathExpressionException e) {throw new RuntimeException("Compile xpath expression occur excetion,please check out your xpath expression.");}}/*** @Author Lanxiaowei* @Title: getNodeText* @Description: 根据xpath获取节点的文本值(只返回匹配的第一个节点的文本值)* @param node* @param expression* @return* @return String* @throws*/public String getNodeText(Node node, String expression) {XPathExpression xpexpreesion = null;try {xpexpreesion = this.xpath.compile(expression);return (String) xpexpreesion.evaluate(node, XPathConstants.STRING);} catch (XPathExpressionException e) {throw new RuntimeException("Compile xpath expression occur excetion,please check out your xpath expression.");}}/*** @Author: Lanxiaowei(736031305@qq.com)* @Title: getMultiNodeText* @Description: 根据xpath获取节点的文本值(若xpath表达式匹配到多个节点,则会提取所有匹配到节点的文本值)* @param @param node* @param @param expression* @param @return* @return List<String>* @throws*/public List<String> getMultiNodeText(Node node, String expression) {NodeList nodeList = selectNodes(node, expression);if(null == nodeList || nodeList.getLength() == 0) {return null;}List<String> list = new ArrayList<String>();for(int i=0; i < nodeList.getLength(); i++) {Node n = nodeList.item(i);String text = n.getTextContent();list.add(text);}return list;}/*** @Author: Lanxiaowei(736031305@qq.com)* @Title: getNodeAttributeValue* @Description: 根据xpath获取节点的属性值(若xpath表达式匹配到多个节点,则只会提取匹配到的第一个节点的属性值)* @param @param node* @param @param expression* @param @param atrributeName* @param @return* @return String* @throws*/public String getNodeAttributeValue(Node node,String expression, String atrributeName) {Node matchNode = selectSingleNode(node, expression);if (null == matchNode) {return null;}Node attNode = matchNode.getAttributes().getNamedItem(atrributeName);if (null == attNode) {return null;}return attNode.getNodeValue();}/*** @Author: Lanxiaowei(736031305@qq.com)* @Title: getMultiNodeAttributeValue* @Description: 根据xpath获取节点的属性值(若xpath表达式匹配到多个节点,则会提取所有匹配到节点的属性值)* @param @param node* @param @param expression      Xpath表达式,如div\span[@class]* @param @param atrributeName   属性名称* @param @return* @return List<String>* @throws*/public List<String> getMultiNodeAttributeValue(Node node, String expression,String atrributeName) {NodeList nodeList = selectNodes(node, expression);if(null == nodeList || nodeList.getLength() == 0) {return null;}List<String> list = new ArrayList<String>();for(int i=0; i < nodeList.getLength(); i++) {Node currentItem = nodeList.item(i);Node attNode = currentItem.getAttributes().getNamedItem(atrributeName);if(null == attNode) {continue;}String val = currentItem.getAttributes().getNamedItem(atrributeName).getNodeValue();list.add(val);}return list;}public static void main(String[] args) throws ParserConfigurationException,SAXException, IOException {/*String fragment = "<data><employee><name>益达</name>"+ "<title>Manager</title></employee></data>";XMLUtils util = new XMLUtils();Document doc = util.fragment2Document(fragment);NodeList nodes = doc.getElementsByTagName("employee");for (int i = 0; i < nodes.getLength(); i++) {Element element = (Element) nodes.item(i);NodeList name = element.getElementsByTagName("name");Element line = (Element) name.item(0);System.out.println("Name: " + line.getNodeName() + ":"+ line.getTextContent());NodeList title = element.getElementsByTagName("title");line = (Element) title.item(0);System.out.println("Name: " + line.getNodeName() + ":"+ line.getTextContent());}*/String fragment = "<data><employee><name id=\"1\">益达</name><name id=\"2\">yida</name>"+ "<title>Manager</title></employee></data>";XMLUtils util = new XMLUtils();Document doc = util.fragment2Document(fragment);List<String> strList = util.getMultiNodeText(doc, "//employee/name[@id]");String s = GerneralUtils.joinCollection(strList);System.out.println(s);strList = util.getMultiNodeAttributeValue(doc, "//employee/name[@id]", "id");s = GerneralUtils.joinCollection(strList);System.out.println(s);}
}

 

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

 

这篇关于有关W3C Document操作的XML工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/327211

相关文章

使用Python自建轻量级的HTTP调试工具

《使用Python自建轻量级的HTTP调试工具》这篇文章主要为大家详细介绍了如何使用Python自建一个轻量级的HTTP调试工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录一、为什么需要自建工具二、核心功能设计三、技术选型四、分步实现五、进阶优化技巧六、使用示例七、性能对比八、扩展方向建

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

使用Java实现通用树形结构构建工具类

《使用Java实现通用树形结构构建工具类》这篇文章主要为大家详细介绍了如何使用Java实现通用树形结构构建工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录完整代码一、设计思想与核心功能二、核心实现原理1. 数据结构准备阶段2. 循环依赖检测算法3. 树形结构构建4. 搜索子

利用Python开发Markdown表格结构转换为Excel工具

《利用Python开发Markdown表格结构转换为Excel工具》在数据管理和文档编写过程中,我们经常使用Markdown来记录表格数据,但它没有Excel使用方便,所以本文将使用Python编写一... 目录1.完整代码2. 项目概述3. 代码解析3.1 依赖库3.2 GUI 设计3.3 解析 Mark

Python使用DrissionPage中ChromiumPage进行自动化网页操作

《Python使用DrissionPage中ChromiumPage进行自动化网页操作》DrissionPage作为一款轻量级且功能强大的浏览器自动化库,为开发者提供了丰富的功能支持,本文将使用Dri... 目录前言一、ChromiumPage基础操作1.初始化Drission 和 ChromiumPage

利用Go语言开发文件操作工具轻松处理所有文件

《利用Go语言开发文件操作工具轻松处理所有文件》在后端开发中,文件操作是一个非常常见但又容易出错的场景,本文小编要向大家介绍一个强大的Go语言文件操作工具库,它能帮你轻松处理各种文件操作场景... 目录为什么需要这个工具?核心功能详解1. 文件/目录存javascript在性检查2. 批量创建目录3. 文件