java操作xml的方法汇总及解析
这篇文章主要介绍了java操作xml的方法汇总及解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一丶常用方法
主要有3个方面,1读取xml文件,2使用xpath根据指定路径获取某一节点数据3,xml和javabean的转换
XmlUtils.java
/**
*和cn.hutool.core.util.XmlUtil许多功能重合,本类可以当做学习的例子
*可以直接使用cn.hutool.core.util.XmlUtil
*
*@authorTimFruit
*@date19-11-2下午5:22
*/
publicclassXmlUtils{
//--------------------------------------
publicstaticDocumentcreateXml(){
returnXmlUtil.createXml();
}
//--------------------------------------
/**
*读取xml文档
*@paramxmlInputStream
*@return
*/
publicstaticDocumentreadXml(InputStreamxmlInputStream){
returnreadXml(xmlInputStream,false);
}
publicstaticDocumentreadXml(InputStreamxmlInputStream,booleanvalidate){//参考mybatisparsing模块
try{
DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();
factory.setValidating(validate);
factory.setNamespaceAware(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setExpandEntityReferences(true);
DocumentBuilderbuilder=factory.newDocumentBuilder();
returnbuilder.parse(xmlInputStream);
}catch(ParserConfigurationExceptione){
thrownewRuntimeException(e);
}catch(SAXExceptione){
thrownewRuntimeException(e);
}catch(IOExceptione){
thrownewRuntimeException(e);
}
}
publicstaticDocumentreadXml(StringxmlStr){
returnXmlUtil.parseXml(xmlStr);//使用hutool
}
//--------------------------------------
//根据路径获取某一节点
publicstaticXPathnewXpath(){
returnXPathFactory.newInstance().newXPath();
}
/**
*根据路径获取某一节点,语法看https://www.w3school.com.cn/xpath/xpath_syntax.asp
*@paramexpression
*@paramroot可以是document,可以是Node等其他节点
*@paramxpath
*@return返回的节点可以修改
*/
publicstaticNodeevalNode(Stringexpression,Objectroot,XPathxpath){
return(Node)evaluate(expression,root,XPathConstants.NODE,xpath);
}
publicstaticNodeListevalNodeList(Stringexpression,Objectroot,XPathxpath){
return(NodeList)evaluate(expression,root,XPathConstants.NODESET,xpath);
}
publicstaticDoubleevalDouble(Stringexpression,Objectroot,XPathxpath){
return(Double)evaluate(expression,root,XPathConstants.NUMBER,xpath);
}
publicstaticBooleanevalBoolean(Stringexpression,Objectroot,XPathxpath){
return(Boolean)evaluate(expression,root,XPathConstants.BOOLEAN,xpath);
}
publicstaticStringevalString(Stringexpression,Objectroot,XPathxpath){
return(String)evaluate(expression,root,XPathConstants.STRING,xpath);
}
publicstaticLongevalLong(Stringexpression,Objectroot,XPathxpath){
returnLong.valueOf(evalString(expression,root,xpath));
}
publicstaticIntegerevalInteger(Stringexpression,Objectroot,XPathxpath){
returnInteger.valueOf(evalString(expression,root,xpath));
}
publicstaticFloatevalFloat(Stringexpression,Objectroot,XPathxpath){
returnFloat.valueOf(evalString(expression,root,xpath));
}
publicstaticShortevalShort(Stringexpression,Objectroot,XPathxpath){
returnShort.valueOf(evalString(expression,root,xpath));
}
privatestaticObjectevaluate(Stringexpression,Objectroot,QNamereturnType,XPathxpath){
try{
returnxpath.evaluate(expression,root,returnType);
}catch(Exceptione){
thrownewRuntimeException("ErrorevaluatingXPath.Cause:"+e,e);
}
}
//--------------------------------------
//转成string
publicstaticStringtoStr(Nodenode){
returntoStr(node,false);
}
publicstaticStringtoStr(Nodenode,booleanisPretty){
returntoStr(node,"utf-8",isPretty);
}
/**
*
*@paramnode
*@paramcharset编码
*@paramisPretty是否格式化输出
*@return
*/
publicstaticStringtoStr(Nodenode,Stringcharset,booleanisPretty){
finalStringWriterwriter=StrUtil.getWriter();
finalintINDENT_DEFAULT=2;
try{
XmlUtil.transform(newDOMSource(node),newStreamResult(writer),charset,isPretty?INDENT_DEFAULT:0);
}catch(Exceptione){
thrownewUtilException(e,"Transxmldocumenttostringerror!");
}
returnwriter.toString();
}
//----------------------------------------
//和javabean转换
publicstaticJSONObjecttoJSONObject(StringxmlStr){
returnXML.toJSONObject(xmlStr);
}
publicstaticJSONObjecttoJSONObject(Nodenode){
StringxmlStr=toStr(node);
returntoJSONObject(xmlStr);
}
publicstaticTtoBean(Nodenode,Classclazz){
returntoJSONObject(node).toBean(clazz);
}
publicstaticNodetoNode(Objectobj){
Stringxml=toXml(obj);
NoderootNode=readXml(xml).getFirstChild();
returnrootNode;
}
publicstaticStringtoXml(Objectobj){
returnXML.toXml(obj);
}
}
二丶测试
@Test
publicvoidreadXmlFromInputStreamTest(){
BufferedInputStreambis=FileUtil.getInputStream("xml/bookstore.xml");
Documentdocument=XmlUtils.readXml(bis);
StringnodeName=document.getFirstChild().getNodeName();
System.out.println(nodeName);
Assert.assertTrue(nodeName.equals("bookstore"));
}
@Test
publicvoidreadXmlStringTest()throwsIOException{
BufferedInputStreambis=FileUtil.getInputStream("xml/bookstore.xml");
StringxmlStr=StreamUtils.copyToString(bis,Charset.defaultCharset());
Documentdocument=XmlUtils.readXml(xmlStr);
StringnodeName=document.getFirstChild().getNodeName();
System.out.println(nodeName);
Assert.assertTrue(nodeName.equals("bookstore"));
}
//--------------------------------------------xpath
/*
https://www.w3school.com.cn/xpath/xpath_syntax.asp
nodename选取此节点的所有子节点。
/从根节点选取。
//从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
.选取当前节点。
..选取当前节点的父节点。
@选取属性。
*/
@Test
publicvoidevalNodeTest(){
BufferedInputStreambis=FileUtil.getInputStream("xml/bookstore.xml");
Documentdocument=XmlUtils.readXml(bis);
XPathxpath=XmlUtils.newXpath();
//1.使用xpath表达式读取根节点
NoderootNode=XmlUtils.evalNode("/bookstore",document,xpath);
Assert.assertEquals("bookstore",rootNode.getNodeName());
//2.使用xpath表达式读取nodeList
NodeListbookNodeList=XmlUtils.evalNodeList("/bookstore/book",document,xpath);
NodebookNode=null;
for(inti=0;ibookList=bookstore.getBook();
Bookbook1=bookList.get(0);
Assert.assertTrue(book1.getTitle().getLang().equals("en"));
Assert.assertTrue(book1.getTitle().getContent().equals("HarryPotter"));
Assert.assertTrue(book1.getAuthor().equals("JK.Rowling"));
Bookbook2=bookList.get(1);
Assert.assertTrue(book2.getTitle().getLang().equals("cn"));
Assert.assertTrue(book2.getTitle().getContent().equals("whereIamfrom"));
Assert.assertTrue(book2.getAuthor().equals("timfruit"));
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。