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

java解析xml出错
xml文档
<?xml version="1.0" encoding="gb2312"?>
<invoice_resp>
<head>
<yyid>320100004056135002</yyid> 
<ywxtid>002</ywxtid > 
<qqsj>20110819161818</qqsj>
<bwlx>02</bwlx>
<swglm>320100004056135</swglm>
<fpdm>232001007717</fpdm> 
<fpfs>1</fpfs>
<fphmq>03539087</fphmq>
<fphmz>03539087</fphmz>
<bwlsh>320100004056655000091235103</bwlsh>
<xysj>2011-08-23 02:21:21</xysj>
<errorcode>0</errorcode>
<errmsg>成功执行</errmsg>
</head>
<invoices>
<invoice>
<fpdm>232001007717</fpdm>
<fphm>03539087</fphm>
<fpzt>1</fpzt>
<errorcode>0</errorcode>
<errmsg>命令执行成功00</errmsg>
</invoice>
</invoices>
</invoice_resp>

---------java code
package com.xml;
import java.io.*; 
import java.util.*; 
import org.dom4j.*; 
import org.dom4j.io.*; 

public class MyXMLReader { 

public static void main(String arge[]) { 
//long lasting = System.currentTimeMillis(); 
String lsh="";
String fpxh="";
String kprq="";
String fpdm="";
String fphm="";
String fpzt="";
try { 
File f=new File("C:\\baowen\\1.xml");
SAXReader reader=new SAXReader();
Document doc=reader.read(f);
Element root=doc.getRootElement();
Element foo;
for(Iterator i=root.elementIterator(); i.hasNext();)
{
foo=(Element)i.next();
System.out.println("lsh:"+foo.elementText("bwlsh"));
System.out.println("fpfs:"+foo.elementText("fpfs"));
System.out.println("xysj:"+foo.elementText("xysj"));
System.out.println("fpdm:"+foo.elementText("fpdm"));
System.out.println("fphmq:"+foo.elementText("fphmq"));
System.out.println("fpzt:"+foo.elementText("fpzt"));
}
}catch(Exception e){
e.printStackTrace();




取不到System.out.println("fpzt:"+foo.elementText("fpzt"));这个值
这个java代码还取两边而且第二边的值全部为空, 我只想取一边把全部值取到

谁指点下刚学

------解决方案--------------------
public Iterator elementIterator()
Returns an iterator over all this elements child elements. 
该方法返回的是foo的子节点,也就是两个,一个是head,一个是invoices
第一遍的foo实际是head结点,第二次是invoices结点
你再通过elementText获取对应名字子节点的text,如果不存在该子节点就为Null了
------解决方案--------------------
可以把Element的名字打印出来,你就知道具体操作到哪里了。
------解决方案--------------------
你可以通过递归遍历获取所有结点并判断是自己要的结点的话就进行操作,大致递归就是
Java code

    public static void print(Element element)  
    {  
        System.out.println(element);  //操作,可以用if(。。。) {xxx}判断之后操作
        List<Element> elements = element.elements();  //childs
        for(Element e : elements)  
        {  
            print(e);  //递归遍历所有子节点
        }  
          
    }

------解决方案--------------------
好深奥的东西!
------解决方案--------------------
探讨

无论是第一边还是第二边都不会取的fpzt的值,不知道为什么谁能帮我写个

------解决方案--------------------
探讨

无论是第一边还是第二边都不会取的fpzt的值,不知道为什么谁能帮我写个