日期:2014-05-20  浏览次数:20761 次

求一段:dom4j 解析xml字符串 代码
<?xml version="1.0" encoding="UTF-8"?>
<ROOT><Information><Name>AAA</Name><Number>BBB</Number><Recording>http://10.15.57.174/wav/2008/10/29/WG37100/ext37102/10.15.57.71!1~R!10292008_064002!37102!67256479!Ext!NA!1179371583!R.wav</Recording><Orders>有</Orders></Information></ROOT>
现有这样一个xml字符串

现在想取出<Recording></Recording>中的字符串 (注:会有多个<Information>...</Information>)

然后将Recording中的字符串存到数组中
在网上找了些资料,但试验时报no protocol 异常,我的eclipse工程是GBK和这个XML的UTF-8有冲突嘛?~
试验代码如下:
  Document doc = null;
try{ 
SAXReader reader = new SAXReader(); 
doc = reader.read(li); //li即为上述xml字符串
Element root = doc.getRootElement();
Element foo;
for(Iterator i = root.elementIterator("Information");i.hasNext();){
foo = (Element) i.next();
list.add(foo.elementText("Recording"));
for(Iterator a = list.iterator();i.hasNext();){
System.out.println(a.next()); }
}
}catch(Exception e){
e.printStackTrace();
}

------解决方案--------------------
public void strChangeXML(String str) throws IOException {
SAXReader saxReader = new SAXReader();
Document document;
try {
document = saxReader.read(new ByteArrayInputStream(str.getBytes()));


http://hi.baidu.com/vjame/blog/item/ecafaa6445a4d9f4f6365455.html 


saxReader.read 的方法是从文件,或者流中读取的,你要看下api
我也不熟,刚查的
原来用过,但忘了

------解决方案--------------------
read

public Document read(String systemId)
throws DocumentException

Reads a Document from the given URL or filename using SAX.

If the systemId contains a ':' character then it is assumed to be a URL otherwise its assumed to be a file name. If you want finer grained control over this mechansim then please explicitly pass in either a URL or a File instance instead of a String to denote the source of the document.
------解决方案--------------------
Invalid byte 1 of 1-byte UTF-8 sequence. Nested exception: Invalid byte 1 of 1-byte UTF-8 sequence.

如果你字符串本身是UTF-8的话,要
document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));

一般处理XML,最好是以字节流读进来,丢给SAX就可以了,不要先转成字符串又转成字节。
------解决方案--------------------
如果字符串li是xml文件的名字,直接用reader.read()即可。
5楼的laorer应经说的非常清楚了。
如果字符串li是xml文件的内容,需要把li转化成流才能作为read方法的参数使用。
你出现上述问题是因为字符串中含有中文字符,但是字符串编码却使用的是本地字符编码,中文系统下可能是gb2312。
为了解决这个问题,你需要指定字符串编码方式为utf-8.
我把eclipse当中的text file encoding改为utf-8(在properties当中设置),然后在java文件
定义
String li = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT><Information><Name>AAA </Name><Number>BBB </Number><Recording>http://10.15.57.174/wav/2008/10/29/WG37100/ext37102/10.15.57.71!1~R!10292008_064002!37102!67256479!Ext!NA!1179371583!R.wav </Recording> <Orders>?有</Orders></Information></ROOT> ";
再把
doc = reader.read(li); 
改为
doc=reader.read(new ByteArrayInputStream(li.getBytes("utf-8")));
其实laorer应经把问题给解决了,只是没有指定字符串的编码方式而已。