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

相关文章

高效录音转文字:2024年四大工具精选!

在快节奏的工作生活中,能够快速将录音转换成文字是一项非常实用的能力。特别是在需要记录会议纪要、讲座内容或者是采访素材的时候,一款优秀的在线录音转文字工具能派上大用场。以下推荐几个好用的录音转文字工具! 365在线转文字 直达链接:https://www.pdf365.cn/ 365在线转文字是一款提供在线录音转文字服务的工具,它以其高效、便捷的特点受到用户的青睐。用户无需下载安装任何软件,只

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念

超强的截图工具:PixPin

你是否还在为寻找一款功能强大、操作简便的截图工具而烦恼?市面上那么多工具,常常让人无从选择。今天,想给大家安利一款神器——PixPin,一款真正解放双手的截图工具。 想象一下,你只需要按下快捷键就能轻松完成多种截图任务,还能快速编辑、标注甚至保存多种格式的图片。这款工具能满足这些需求吗? PixPin不仅支持全屏、窗口、区域截图等基础功能,它还可以进行延时截图,让你捕捉到每个关键画面。不仅如此

intellij idea generatorConfig.xml

generatorConfig.xml <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-ge

动手学深度学习【数据操作+数据预处理】

import osos.makedirs(os.path.join('.', 'data'), exist_ok=True)data_file = os.path.join('.', 'data', 'house_tiny.csv')with open(data_file, 'w') as f:f.write('NumRooms,Alley,Price\n') # 列名f.write('NA

线程的四种操作

所属专栏:Java学习        1. 线程的开启 start和run的区别: run:描述了线程要执行的任务,也可以称为线程的入口 start:调用系统函数,真正的在系统内核中创建线程(创建PCB,加入到链表中),此处的start会根据不同的系统,分别调用不同的api,创建好之后的线程,再单独去执行run(所以说,start的本质是调用系统api,系统的api

Java IO 操作——个人理解

之前一直Java的IO操作一知半解。今天看到一个便文章觉得很有道理( 原文章),记录一下。 首先,理解Java的IO操作到底操作的什么内容,过程又是怎么样子。          数据来源的操作: 来源有文件,网络数据。使用File类和Sockets等。这里操作的是数据本身,1,0结构。    File file = new File("path");   字

PR曲线——一个更敏感的性能评估工具

在不均衡数据集的情况下,精确率-召回率(Precision-Recall, PR)曲线是一种非常有用的工具,因为它提供了比传统的ROC曲线更准确的性能评估。以下是PR曲线在不均衡数据情况下的一些作用: 关注少数类:在不均衡数据集中,少数类的样本数量远少于多数类。PR曲线通过关注少数类(通常是正类)的性能来弥补这一点,因为它直接评估模型在识别正类方面的能力。 精确率与召回率的平衡:精确率(Pr

husky 工具配置代码检查工作流:提交代码至仓库前做代码检查

提示:这篇博客以我前两篇博客作为先修知识,请大家先去看看我前两篇博客 博客指路:前端 ESlint 代码规范及修复代码规范错误-CSDN博客前端 Vue3 项目开发—— ESLint & prettier 配置代码风格-CSDN博客 husky 工具配置代码检查工作流的作用 在工作中,我们经常需要将写好的代码提交至代码仓库 但是由于程序员疏忽而将不规范的代码提交至仓库,显然是不合理的 所

MySQL——表操作

目录 一、创建表 二、查看表 2.1 查看表中某成员的数据 2.2 查看整个表中的表成员 2.3 查看创建表时的句柄 三、修改表 alter 3.1 重命名 rename 3.2 新增一列 add 3.3 更改列属性 modify 3.4 更改列名称 change 3.5 删除某列 上一篇博客介绍了库的操作,接下来来看一下表的相关操作。 一、创建表 create