易截截图软件、单文件、免安装、纯绿色、仅160KB

XML字符串和XML DOCUMENT的相互转换【转】

在做一般的XML数据交换过程中,我更乐意传递XML字符串,而不是格式化的XML Document。这就涉及到XML字符串和Xml Document的转换问题,说白了这是个很简单的问题,本文就各种XML解析器分别列举如下,以方便自己今后查阅。
一、使用最原始的javax.xml.parsers,标准的jdk api
// 字符串转XML
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);
//XML转字符串
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();
这里的XML DOCUMENT为org.w3c.dom.Document
  二、使用dom4j后程序变得更简单
// 字符串转XML
String xmlStr = "......";
Document document = DocumentHelper.parseText(xmlStr);
// XML转字符串
Document document = ...;
String text = document.asXML();
这里的XML DOCUMENT为org.dom4j.Document
  三、使用JDOM
JDOM的处理方式和第一种方法处理非常类似
//字符串转XML
String xmlStr = ".....";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
Document doc = (new SAXBuilder()).build(is);
//XML转字符串
Format format = Format.getPrettyFormat();
format.setEncoding("gb2312");//设置xml文件的字符为gb2312,解决中文问题
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
xmlout.output(doc,bo);
String xmlStr = bo.toString();
这里的XML DOCUMENT为org.jdom.Document
  四、JAVASCRIPT中的处理
//字符串转XML
var xmlStr = ".....";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(xmlStr);
//可以处理这个xmlDoc了
var name = xmlDoc.selectSingleNode("/person/name");
alert(name.text);
//XML


相关文档:

php之XML转数组函数

<?
/**
* xml2array() will convert the given XML text to an array in the XML structure.
* Link: http://www.bin-co.com/php/scripts/xml2array/
* Arguments : $contents - The XML text
* $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the ......

Delphi与XML文档

同步程序案例
procedure TGetOrderThread.PostDB(webnr:WideString);
var
  Err: String;
  SetWebnr:WideString;
  xmlDoc: IXMLDocument;
  root: IXMLNode;
  rowc: IXMLNode;//记录数
  rows: IXMLNodeList;//主记录列表
  row: IXMLNode;
  drows: IXMLNodeList;// ......

python minidom 写xml示例

以下是一个通过minidom模块写文件的完整示例,是在最近做的项目Walle上面用到的,这个示例的目的是生成一个如下的格式的xml,文件格式为无BOM utf-8。
生成xml文件格式:
<?xml version="1.0" encoding="utf-8"?> 
<coverages> 
    <coverage> 
    ......

格式化XML:输出有缩进效果的XML字符串

1. 一般情况下使用以下代码即可将XML字符串重新格式化:
        private string FormatXml(string source)
        {
            StringBuilder  ......

用XmlReader 取xml文件节点的值

在项目中,同一个配置在不同的目录下要有不同的值,而目录又是不确定的,这时就需要将配置信息存放在相应的目录中,在运行时根据路径去取
方法:用xml文件存储,放在使用目录下,用下面方法获取配置信息
public class yzzConfig
{
/// <summary>
/// 获取Xml文件配置信息
/// ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号