有关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实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

Java中的工具类命名方法

《Java中的工具类命名方法》:本文主要介绍Java中的工具类究竟如何命名,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java中的工具类究竟如何命名?先来几个例子几种命名方式的比较到底如何命名 ?总结Java中的工具类究竟如何命名?先来几个例子JD

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Spring 基于XML配置 bean管理 Bean-IOC的方法

《Spring基于XML配置bean管理Bean-IOC的方法》:本文主要介绍Spring基于XML配置bean管理Bean-IOC的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录一. spring学习的核心内容二. 基于 XML 配置 bean1. 通过类型来获取 bean2. 通过

MySql match against工具详细用法

《MySqlmatchagainst工具详细用法》在MySQL中,MATCH……AGAINST是全文索引(Full-Textindex)的查询语法,它允许你对文本进行高效的全文搜素,支持自然语言搜... 目录一、全文索引的基本概念二、创建全文索引三、自然语言搜索四、布尔搜索五、相关性排序六、全文索引的限制七