xml 字符串和xml Document相互转换、xml Document内容输出到http response


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Test {

/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) {
try {
// 使用最原始的javax.xml.parsers,标准的jdk api
// 字符串转XML
String xmlStr = "<xml>content</xml>";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);

// XML转字符串
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
// 编码设置
t.setOutputProperty("encoding", "GB2312");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
xmlStr = bos.toString();

// 把org.w3c.dom.Document doc的xml内容输出到http response
response.setContentType("text/xml");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 1);

DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(response.getOutputStream());

t.transform(source, result);
} catch (Exception e) {
System.out.println(e.getMessage());
}


// 使用dom4j后程序变得更简单
// 字符串转XML
String xmlStr1 = "<xml>content1</xml>";
org.dom4j.Document.Document document = DocumentHelper.parseText(xmlStr1);

// XML转字符串
org.dom4j.Document.Document document = ...;
String text = document.asXML();
}
}

当xmlStr的内容为aa时,系统会报错误: [Fatal Error] :1:1: Content is not allowed in prolog.
当xmlStr的内容为<xml>content</xml>bb时,系统会报错误[Fatal Error] :1:19: Content is not allowed in trailing section.
都是提示[color=blue]:m:n,m行n列所在位置的内容不是正常的xml内容[/color]

参考:[url=http://lwbpeter.blog.163.com/blog/static/385082112010103112216129/]XML字符串和XML DOCUMENT的相互转换([/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用HTTP请求传输XML对象。在Java中,可以使用一些类库来发送HTTP请求和解析XML数据,如Apache HttpClient和DOM解析器。 首先,我们需要使用Apache HttpClient类库来发送HTTP请求。可以使用HttpClient的Post请求来发送XML数据。首先创建一个HttpClient对象,然后创建一个HttpPost对象,并将请求URL作为参数传递给HttpPost构造函数。接下来,设置请求头的Content-Type为"application/xml",表示要发送的数据是XML格式。然后,将XML数据作为请求的实体传递给HttpPost对象,并执行请求。 ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpXmlClient { public static void main(String[] args) throws Exception { String xmlData = "<xml><name>John</name><age>25</age></xml>"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://example.com/api"); StringEntity entity = new StringEntity(xmlData, "UTF-8"); entity.setContentType("application/xml"); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseXml = EntityUtils.toString(responseEntity, "UTF-8"); //对返回的XML数据进行解析处理 } } } ``` 接下来,我们需要使用一种XML解析器来解析返回的XML数据。可以使用Java标准库中的DOM解析器。首先,创建一个DocumentBuilderFactory对象来获取DocumentBuilder实例。然后,使用DocumentBuilder的parse方法将XML字符串转换Document对象。最后,可以使用Document对象的相关方法来获取XML中的数据。 ```java import org.w3c.dom.Document; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.StringReader; public class XmlParser { public static void main(String[] args) throws Exception { String responseXml = "<response><message>Success</message></response>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(responseXml))); String message = document.getElementsByTagName("message").item(0).getTextContent(); System.out.println("Message: " + message); } } ``` 通过以上代码,我们可以使用Java发送HTTP请求并传输XML对象,并使用DOM解析器解析返回的XML数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值