关于XML字符串和XML Document之间的转换
发布时间:2020-12-16 06:02:56 所属栏目:百科 来源:网络整理
导读:在web项目中,XML作为一种重要的数据存储和传输介质,被广泛使用。XML文件,XML字符串和XML Document对象是XML存在的三种形式,XML文件无需多言,和普通的文本并无二致;倒是在做一般的XML数据交换过程中,经常要使用XML字符串和XML Document对象,因此在这
在web项目中,XML作为一种重要的数据存储和传输介质,被广泛使用。XML文件,XML字符串和XML Document对象是XML存在的三种形式,XML文件无需多言,和普通的文本并无二致;倒是在做一般的XML数据交换过程中,经常要使用XML字符串和XML Document对象,因此在这两种形式之间进行转化成为了使用XML的必备技术。在所有操控XML的技术中,都提供了这两种形式XML之间的转换方法。
下面我就各种XML技术对此问题的解决方法做个总结,和大家分享,也方便自己今后查阅。
一,使用JDOM(这是我最常使用的一种技术)
1.字符串转Document对象
String xmlStr =
".....";
StringReader sr = new StringReader(xmlStr); InputSource is = new InputSource(sr); Document doc = ( new SAXBuilder()).build(is);
Format format = Format.getPrettyFormat();
注:Document为org.jdom.Document
format.setEncoding( "gb2312"); //设置xml文件的字符为gb2312,解决中文问题 XMLOutputter xmlout = new XMLOutputter(format); ByteArrayOutputStream bo = new ByteArrayOutputStream(); xmlout.output(doc,bo); String xmlStr = bo.toString();
二,使用最原始的javax.xml.parsers,标准的jdk api
1.字符串转Document对象
String xmlStr =
"......";
StringReader sr = new StringReader(xmlStr); InputSource is = new InputSource(sr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc = builder.parse(is);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(); t.setOutputProperty( "encoding","GB23121"); //解决中文问题,试过用GBK不行 ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform( new DOMSource(doc), new StreamResult(bos)); String xmlStr = bos.toString();
三,使用dom4j(这是最简单的方法)
1.字符串转Document对象
String xmlStr =
"......";
2.Document对象转字符串
Document document = DocumentHelper.parseText(xmlStr);
Document document = ...;
String text = document.asXML();
四,在JavaScript中的处理
1.字符串转Document对象
var xmlStr =
".....";
var xmlDoc = new ActiveXObject( "Microsoft.XMLDOM"); xmlDoc.async= false; xmlDoc.loadXML(xmlStr); //可以处理这个xmlDoc了 var name = xmlDoc.selectSingleNode( "/person/name"); alert(name.text);
var xmlDoc = ......;
var xmlStr = xmlDoc.xml 本文出自 “夜狼” 博客,请务必保留此出处http://www.52php.cn/article/p-hmdoxujm-qw.html xml格式字符串与java对象互转
import java.lang.reflect.Field; import java.util.List; import com.thoughtworks.xstream.XStream; public class XmlUtil { // 所有需要注册的类的配置,public static final String CONFIGFILE = new GetClassPath() .getMyConfigPath() + "/xml.prop"; private static XStream xs = null; private static XmlUtil xmlUtil = null; private XmlUtil() { try { // 获取所有需要与处理的java完整名 List list = FileUtil.readFile(CONFIGFILE); //初始化xs xs = alias(list); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获得实例 * @return */ public static synchronized XmlUtil getInstance() { if(null == xmlUtil){ xmlUtil = new XmlUtil(); } return xmlUtil; } /** * 根据类名做反射 * * @param list * 类完整名 * @return * @throws ClassNotFoundException */ public XStream alias(List list) throws ClassNotFoundException { XStream xs = new XStream(); for (int i = 0; i < list.size(); i++) { Object obj; try { obj = Class.forName((String) list.get(i)).newInstance(); Class zz = obj.getClass(); aliasAtt(xs,zz); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return xs; } /** * 对类进行xml解析配置 * * @param xs * @param z * class对象 */ public void aliasAtt(XStream xs,Class z) { if (null == z) { return; } // 类名注册 xs.alias(z.getSimpleName(),z); Field[] field = z.getDeclaredFields(); // 类中成员变量注册,继承的不注册 for (int i = 0; i < field.length; i++) { xs.aliasField(field[i].getName(),field[i].getName()); } } /** * xml 格式字符串转换为对象 * @param str * @return */ public Object xmlToObject(String str) { return xs.fromXML(str); } /** * 对象转换为xml格式字符串 * @param obj * @return */ public String objToXml(Object obj) { return xs.toXML(obj); } } FileUtil.readFile()方法如下 /** * 读取文件 * * @param filePath * 文件完整名 * @return 文件内容 * @throws IOException */ public static List readFile(String filePath) { List list = new ArrayList(); FileInputStream fs = null; InputStreamReader isr = null; BufferedReader br = null; try { fs = new FileInputStream(filePath); isr = new InputStreamReader(fs); br = new BufferedReader(isr); String data = ""; while ((data = br.readLine()) != null) { list.add(data.trim()); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (isr != null) isr.close(); if (fs != null) fs.close(); } catch (IOException e) { e.printStackTrace(); } } return list; } Test Printdata pd = new Printdata(); pd.setPrintFileList(printFileList); pd.setAuto("1"); pd.setBillReceiver("billReceiver"); pd.setCustId("cust_id"); pd.setYear("2011"); pd.setMonth("11"); List list = FileUtil.readFile(XmlUtil.CONFIGFILE); XmlUtil xmlUtil = XmlUtil.getInstance(); String xml = xmlUtil.objToXml(pd);//对象至xml System.out.println(xml); Printdata obj = (Printdata)xmlUtil.xmlToObject(xml);//xml至对象
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |