package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.baje.sz.util.Doc;
public class Dom4jSoap {
/**
* 取根元素
* @param path
* @return
* @throws DocumentException
*/
public static Element getRoot(String path) throws DocumentException{
Document document;
SAXReader reader=new SAXReader();
document=reader.read(new File(path));
Element root=document.getRootElement();
return root;
}
public static void readSoap(Element element){
if(element.elements().size()==0){
System.out.println(element.getName()+"*="+element.getText());
return;
}
for (Iterator<Element> iter=element.elementIterator();iter.hasNext();) {
Element ele=iter.next();
if(ele.getParent().getName().equalsIgnoreCase("Envelope")){
System.out.println("-------------------------Envelope的直接子元素:"+ele.getName()+",,"+ele.attributeValue("xmlns"));
}
System.out.println(ele.getName()+"%="+ele.getText().trim());
if(ele.elements().size()!=0){
System.out.println(("element "+ele.getName()+" has "+ele.elements().size())+(ele.elements().size()==1?" subTag it is ":" subTags there are"));
readSoap(ele);
}
if(ele.getName().equals("UserName")){
System.out.println("path="+ele.getPath());
}
}
}
/**
* 获取节点的元素的值
* @param filename
* @param xmlpath="//*[name()='Date'][@id='aa']/*[name()='aaa']"
* @return
*/
public static String getElementText(String filename, String xmlpath,String encode) {
try {
Document document;
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
document=reader.read(in,encode);
List list = document.selectNodes(xmlpath);
for(Iterator iter = list.iterator();iter.hasNext();){
Element e = (Element)iter.next();
return e.getText();
}
return "";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 取指定节点元素的属性的值
* @param filename
* @param xmlpath="//*[name()='Date'][@id='bb']/@ac"
* @param encode
* @return
*/
public static String getAttributesText(String filename, String xmlpath,String encode){
try {
Document document;
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
document=reader.read(in,encode);
List list = document.selectNodes(xmlpath);
for(Iterator iter=list.iterator();iter.hasNext();){
Attribute a = (Attribute)iter.next();
return a.getText();
}
return "";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 获取指定元素下所有元素值到LIST
* @param filename
* @param xmlpath="//*[name()='Date']"
* @param encode
* @return
*/
public static List xmlElement2List(String filename,String xmlpath,String encode) {
try {
List xmllist = new ArrayList();
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
List list = document.selectNodes(xmlpath);
for(Iterator iter=list.iterator();iter.hasNext();){
Element e = (Element)iter.next();
Doc doc = new Doc();
for(Iterator iter2=e.elementIterator();iter2.hasNext();){
Element e2=(Element)iter2.next();
doc.put(e2.getName(), e2.getText());
}
xmllist.add(doc);
}
return xmllist;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取指定元素的属性值
* @param filename
* @param xmlpath="//*[name()='Date']"
* @param encode
* @return
*/
public static List xmlAttributes2List(String filename,String xmlpath,String encode) {
try {
List xmllist = new ArrayList();
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
List list = document.selectNodes(xmlpath);
for(Iterator iter=list.iterator();iter.hasNext();){
Element e = (Element)iter.next();
Doc doc = new Doc();
for(Iterator iter2=e.attributeIterator();iter2.hasNext();){
Attribute attribute = (Attribute)iter2.next();
doc.put(attribute.getName(),attribute.getValue());
}
xmllist.add(doc);
}
return xmllist;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 取指定节点的子元素存到DOC
* @param filename
* @param xmlpath="//*[name()='Date'][@id='bb']",
* @param encode
* @return
*/
public static Doc xmlElement2Doc(String filename,String xmlpath,String encode){
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
List list = document.selectNodes(xmlpath);
Doc doc = new Doc();
for(Iterator iter = list.iterator();iter.hasNext();){
Element e = (Element)iter.next();
for(Iterator iter2 = e.elementIterator();iter2.hasNext();){
Element e2 = (Element)iter2.next();
doc.put(e2.getName(), e2.getText());
}
}
return doc;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 取指定节点的属性值到DOC
* @param filename
* @param xmlpath="//*[name()='Date'][@id='bb']"
* @param encode
* @return
*/
public static Doc xmlAttribute2Doc(String filename,String xmlpath,String encode){
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
List list = document.selectNodes(xmlpath);
Doc doc = new Doc();
for(Iterator iter = list.iterator();iter.hasNext();){
Element e =(Element)iter.next();
for(Iterator iter2=e.attributeIterator();iter2.hasNext();){
Attribute a = (Attribute)iter2.next();
doc.put(a.getName(), a.getValue());
}
}
return doc;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* XML文件转为STRING
* @param filename
* @param encode
* @return
*/
public static String xml2string(String filename,String encode){
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
return document.asXML();
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* STRING转为XML
* @param str
* @return
*/
public static Document string2xml(String str){
try{
Document document = DocumentHelper.parseText(str);
return document;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 创建XML文件
* @param document
* @param filepath
* @param encode
* @return
*/
public static int createXmlFile(Document document,String filepath,String encode){
XMLWriter writer = null;
try{
File file = new File(filepath);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encode);
writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file),encode), format);
writer.write(document);
writer.close();
return 0;
}catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 将LIST数据写入到节点元素值
* @param list
* @param filepath
* @param xmlroot
* @param row
* @param encode
* @return
*/
public static int createXmlList2Element(List list, String filepath,String xmlroot,String row,String encode) {
try {
if (xmlroot.equals("")){
xmlroot="xml";
}
if (row.equals("")){
row="row";
}
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement(xmlroot);
Element rowxml,index;
if(list != null && !list.isEmpty()) {
for(Iterator its2 = list.iterator();its2.hasNext();) {
Doc rowDoc = (Doc)its2.next();
Set set = rowDoc.keySet();
rowxml = rootElement.addElement(row);
for (Iterator its = set.iterator(); its.hasNext();) {
String key = (String) its.next();
String values = rowDoc.get(key);
index = rowxml.addElement(key);
index.setText(String.valueOf(values));
}
}
}
createXmlFile(document,filepath,encode);
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 根据XPATH插入LIST的值到指定节点元素值
* @param list
* @param filepath
* @param xmlpath
* @param row
* @param attrDoc=row节点属性KEY VALUE
* @return
*/
public static int list2Element(List list ,String filepath,String xmlpath,String row,Doc attrDoc, String encode){
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filepath));
Document document = reader.read(in,encode);
/** 先用xpath查找对象 */
List xlist = document.selectNodes(xmlpath);
Iterator iter = xlist.iterator();
if(iter.hasNext()){
Element e = (Element)iter.next();
Element e2=e.addElement(row);
if(attrDoc!=null && !attrDoc.isEmpty()){
Set aset = attrDoc.keySet();
for(Iterator aits = aset.iterator();aits.hasNext();){
String akey=(String)aits.next();
e2.addAttribute(akey, attrDoc.get(akey));
}
}
if(list!=null && !list.isEmpty()){
for(Iterator its=list.iterator();its.hasNext();){
Doc doc = (Doc)its.next();
Set set = doc.keySet();
for(Iterator its2=set.iterator();its2.hasNext();){
String key = (String)its2.next();
String values = doc.get(key);
Element e3=e2.addElement(key);
e3.setText(values);
}
}
}
}
createXmlFile(document,filepath,encode);
return 0;
}catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 将LIST数据写入到节点属性值
* @param list
* @param filepath
* @param xmlroot
* @param row
* @param encode
* @return
*/
public static int createXmlList2Attrbute(List list, String filepath,String xmlroot,String row,String encode) {
try {
if (xmlroot.equals("")){
xmlroot="xml";
}
if (row.equals("")){
row="row";
}
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement(xmlroot);
Element rowxml;
if(list != null && !list.isEmpty()) {
for(Iterator its2 = list.iterator();its2.hasNext();) {
Doc rowDoc = (Doc)its2.next();
Set set = rowDoc.keySet();
rowxml = rootElement.addElement(row);
for (Iterator its = set.iterator(); its.hasNext();) {
String key = (String) its.next();
String values = rowDoc.get(key);
rowxml.addAttribute(key,values);
}
}
}
createXmlFile(document,filepath,encode);
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 根据XPATH修改指定节点的属性值
* @param filepath
* @param xmlpath
* @param row
* @param attrDoc
* @param encode
* @return
*/
public static int doc2attrbute(String filepath,String xmlpath,String row,Doc attrDoc, String encode){
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filepath));
Document document = reader.read(in,encode);
/** 先用xpath查找对象 */
List xlist = document.selectNodes(xmlpath);
Iterator iter = xlist.iterator();
if(iter.hasNext()){
Element e = (Element)iter.next();
Element e2=e.addElement(row);
if(attrDoc!=null && !attrDoc.isEmpty()){
Set aset = attrDoc.keySet();
for(Iterator aits = aset.iterator();aits.hasNext();){
String akey=(String)aits.next();
e2.addAttribute(akey, attrDoc.get(akey));
}
}
}
createXmlFile(document,filepath,encode);
return 0;
}catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 根据XPATH修改指定节点元素值
* @param filename
* @param xmlpath="//*[name()='Date'][@id='aa']/*[name()='aaa']"
* @param value
* @param encode
* @return
*/
public static int ModiXmlElement(String filename,String xmlpath,String value,String encode){
int returnValue = -1;
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
/** 先用xpath查找对象 */
List list = document.selectNodes(xmlpath);
Iterator iter = list.iterator();
while(iter.hasNext()){
Element ownerElement = (Element)iter.next();
ownerElement.setText(value);
}
try{
/** 将document中的内容写入文件中 */
createXmlFile(document,filename,encode);
/** 执行成功,需返回0 */
returnValue = 0;
}catch(Exception ex){
ex.printStackTrace();
}
}catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
/**
* 根据XPATH修改指定节点的指定属性值
* @param filename
* @param xmlpath="//*[name()='Date'][@id='aa']"
* @param node
* @param value
* @param encode
* @return
*/
public static int ModiXmlFileAttrbute(String filename,String xmlpath,String node,String value,String encode){
int returnValue = -1;
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
/** 修改内容之一: 如果book节点中show参数的内容为yes,则修改成no */
/** 先用xpath查找对象 */
// List list = document.selectNodes("/books/book/@show" );
List list = document.selectNodes(xmlpath);
Iterator iter = list.iterator();
while(iter.hasNext()){
Element e = (Element)iter.next();
e.addAttribute(node,value);
}
try{
/** 将document中的内容写入文件中 */
createXmlFile(document,filename,encode);
/** 执行成功,需返回0 */
returnValue = 0;
}catch(Exception ex){
ex.printStackTrace();
}
} catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
/**
* 删除指定节点
* @param filename
* @param xmlpath
* @param value
* @param encode
* @param i,1=0为删除当前row节点,1为删除row父节点
* @return
*/
public static int delElement(String filename,String xmlpath,String row,String value,String encode,int i){
int returnValue=-1;
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
List list = document.selectNodes(xmlpath);
for(Iterator its = list.iterator();its.hasNext();){
Element e = (Element)its.next();
for(Iterator iter2=e.elementIterator(row);iter2.hasNext();){
Element e2=(Element)iter2.next();
if(e2.getText().equals(value)){
if(i==0){
e.remove(e2);
}else if(i==1){
e.getParent().remove(e);
}
}
}
}
createXmlFile(document,filename,encode);
returnValue=0;
} catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
/**
* 删除指定属性的节点,xmlpath包含属性值
* @param filename
* @param xmlpath="//*[name()='Dates']/*[name()='Date'][@ac='7788']"
* @param encode
* @return
*/
public static int delAttrbute(String filename,String xmlpath,String encode){
int returnValue=-1;
try{
SAXReader reader=new SAXReader();
InputStream in = new FileInputStream(new File(filename));
Document document = reader.read(in,encode);
List list = document.selectNodes(xmlpath);
for(Iterator its = list.iterator();its.hasNext();){
Element e = (Element)its.next();
e.getParent().remove(e);
}
createXmlFile(document,filename,encode);
returnValue=0;
}catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
public static void main(String[] args) throws DocumentException {
//String path1="F:/workspace/HelloWorlds/aa.xml";
String path="F:/workspace/HelloWorlds/cc.xml";
//System.out.println(Dom4jSoap.getElementText(path1, "/soap:Envelope/soap:Body/*[name()='Login']/*[name()='loginRequest']/*[name()='UserName']","uft-8"));
//System.out.println(Dom4jSoap.getElementText(path, "//*[name()='Date'][@id='aa']/*[name()='aad']","uft-8"));//"//"表示从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
//System.out.println(Dom4jSoap.getAttributesText(path,"//*[name()='Date'][@id='bb']/@ac","utf-16"));
//System.out.println(Dom4jSoap.getElementText(path, "/soap:Envelope/soap:Body/*[name()='GetHotelInventoryResult']/*[name()='Hotels']/*[name()='Hotel']/*[name()='Rooms']/*[name()='RoomType']/*[name()='Dates']/*[name()='Date'][@di='aa']/*[name()='aad']","utf-16"));
//System.out.println(Dom4jSoap.xmlElement2List(path,"//*[name()='Date']","utf-16"));
//System.out.println(Dom4jSoap.xmlAttributes2List(path,"//*[name()='Date']","utf-16"));
//Dom4jSoap.xmlElement2Doc(path,"//*[name()='Date'][@id='bb']","utf-16");
//Dom4jSoap.xmlAttribute2Doc(path,"//*[name()='Date'][@id='bb']","utf-16");
//System.out.println(Dom4jSoap.xml2string(path,"utf-16"));
//Document document = Dom4jSoap.string2xml("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><person id=\"aa\"><name>afds</name></person></soap:Body></soap:Envelope>");
//Dom4jSoap.createXmlFile(document, "F:/workspace/HelloWorlds/dd.xml", "utf-16");
//List list = new ArrayList();
//Doc doc = new Doc();
//doc.put("aa", 1);
//doc.put("bb", 2);
//list.add(doc);
//doc.put("aa", 11);
//doc.put("bb", 12);
//list.add(doc);
//Dom4jSoap.createXmlList2Element(list, "F:/workspace/HelloWorlds/dd.xml", "test", "room", "utf-8");
//Dom4jSoap.ModiXmlElement("F:/workspace/HelloWorlds/cc.xml", "//*[name()='Date'][@id='aa']/*[name()='aaa']", "222", "utf-16");
//Dom4jSoap.ModiXmlFileAttrbute("F:/workspace/HelloWorlds/cc.xml", "//*[name()='Date'][@id='aa']","ac", "22232", "utf-16");
/**
*
List list = new ArrayList();
Doc doc = new Doc();
doc.put("AvailableDate", 1);
doc.put("AvailableAmount", 2);
doc.put("RoomInvStatusCode", 3);
doc.put("IsOverBooking", 4);
doc.put("BookingStartDate", 5);
doc.put("BookingEndDate", 6);
doc.put("BookingBeginTime", 7);
doc.put("BookingEndTime", 8);
list.add(doc);
Doc adoc = new Doc();
adoc.put("id", "3322");
adoc.put("ac", "7788");
Dom4jSoap.list2Element(list, "F:/workspace/HelloWorlds/cc.xml", "//*[name()='Dates']", "Date",adoc, "utf-16");
*/
/**
*
Doc adoc = new Doc();
adoc.put("id", "3322");
adoc.put("ac", "7788");
Dom4jSoap.doc2attrbute("F:/workspace/HelloWorlds/cc.xml", "//*[name()='Dates']", "Date",adoc, "utf-16");
*/
//Dom4jSoap.delElement("F:/workspace/HelloWorlds/cc.xml", "//*[name()='Dates']/*[name()='Date']","bbt", "7", "utf-16",1);
Dom4jSoap.delAttrbute("F:/workspace/HelloWorlds/cc.xml", "//*[name()='Dates']/*[name()='Date'][@ac='7788']", "utf-16");
}
}
分享到:
相关推荐
XPath是XML文档遍历和查询的强大工具,它允许开发者通过路径表达式来选取XML文档中的节点。本主题将深入探讨如何使用Java中的JDOM库来实现XPath解析,从而高效地提取XML数据。 JDOM是一个纯Java的XML处理库,它提供...
标题提到的"xml转对象封装的简单与复杂xml的转化写法"主要涉及以下知识点: 1. **JDOM库**:JDOM是Java Document Object Model的缩写,它提供了一种在内存中表示XML文档的方式,通过创建SAXBuilder或DOMBuilder实例...
首先,我们需要在JSP页面中引入处理XML的库,通常是Java API for XML Processing (JAXP),它包含了DOM(Document Object Model)、SAX(Simple API for XML)和XPath等解析器。在JSP文件的顶部,可以添加以下指令来...
具体的方法是使用DOMXPath::query()方法,传入我们所期望的XPath路径表达式,来找到所需的元素。该方法会返回一个DOMNodeList对象,后者可以被用来访问所有匹配查询的节点列表。下面是使用XPath查询的示例代码: ``...
官方指南通常是最权威的学习资源,它会涵盖XML的起源、基本元素结构、命名空间、属性、注释、处理指令、实体引用、DTD(文档类型定义)、XML Schema、XPath、XSLT等核心概念。此外,还可能讲解了XML解析器的工作原理...
2. 强大的处理能力:XML文档可以通过DOM(Document Object Model)、XPath(XML Path Language)和XSLT等工具进行解析和操作。 3. 可扩展性:XML允许自定义标签,适用于各种领域,如电子书(EPUB)、地图数据(KML...
所以我们相信,XML做为一种先进的数据处理方法,将使网络跨越到一个新的境界。 六. XML的严格格式 吸取HTML松散格式带来的经验教训,XML一开始就坚持实行"良好的格式"。 我们先看HTML的一些语句,这些语句在HTML中...
XPATH 是一门在 XML 文档中查找信息的语言,用于在 XML 文档中对元素和属性进行遍历。它是基于 XML 文档的树结构,并提供了浏览树的能力,通过多样的标准来选择节点。XPATH 语言支持在浏览器中使用,主流的浏览器都...
- **org.jdom.xpath** 提供了对XML文档进行XPath查询的方法。 #### 二、JDOM类说明 JDOM的核心类包括但不限于: - **Attribute**: 表示XML文档中的属性。 - **CDATA**: 表示CDATA区段。 - **Comment**: 表示XML...
而XML查询语言如XQuery和XPath等通过使用正则路径表达式来进行查询,这些查询语言虽能够提高数据处理的灵活性,却仍旧无法完全克服传统查询方法的低效问题。至于XML数据库索引技术,DataGuides和T2index等优化方法...
- **说明**: 此方法是`$(document).ready()`的一种快捷写法,用于指定当文档完全加载后执行的函数。可以定义多个`$(fn)`,它们将在文档加载完成时按顺序依次执行。 - **参数**: `fn` —— 函数,当文档加载完成时...
#### 四、JavaScript处理 **1. click()** - **说明**: 为元素绑定点击事件处理函数。 - **示例**: ```javascript $("a").click(function() { alert("Hello world!"); }); ``` #### 五、动态效果 **1. ...
{14.4}dom4j}{207}{section.14.4} {14.5}XPath}{210}{section.14.5} {14.6}apache.commons}{211}{section.14.6} {15}sqlite3}{213}{chapter.15} {16}Web基础}{215}{chapter.16} {16.1}...