使用dom4j或mycila读取XML

时间:2015-05-07 09:55:14

标签: java xml

我有以下xml作为字符串,但我在循环方式读取参数" PrdInfoTable"和" OrdInfoTable"因为它们是动态的所以我需要把它读成一个arraylist或者什么。我尝试了几种方法,但仍无法完成。我怎么能这样做?

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
    <GetCardResponse xmlns="http://tempuri.org/">
        <GetCardResult>
            <ReturnResult>
                <Return>
                    <ReturnMsgNo>1</ReturnMsgNo>
                    <ReturnMsg>交易成功</ReturnMsg>
                </Return>
                <GetCardResult>
                    <OrdTable>
                        <Facno>1234</Facno>
                        <TrdDate>2015/5/6 11:04:20</TrdDate>
                        <TrdSeq>ABCD1234</TrdSeq>
                        <TrdBarCode>123456789</TrdBarCode>
                    </OrdTable>
                    <PrdTable>
                        <GameFacName></GameFacName>
                        <PrdName>abc123</PrdName>
                        <CardId>ABCD012345</CardId>
                        <CardPwd>KKSDHASBDH</CardPwd>
                        <ExpDate>2015/02/12</ExpDate>
                    </PrdTable>
                    <PrdInfoTable>
                        <PrdNote>* 測12346666666666666666666666666666666</PrdNote>
                    </PrdInfoTable>
                    <PrdInfoTable>
                        <PrdNote>* 測56787777777777777777777</PrdNote>
                    </PrdInfoTable>
                    <PrdInfoTable>
                        <PrdNote>* 測12345611111111111111111</PrdNote>
                    </PrdInfoTable>
                    <OrdInfoTable>
                        <TxetContent>測1111111111111111111111111111111111111111</TxetContent>
                    </OrdInfoTable>
                    <OrdInfoTable>
                        <TxetContent>22222測22222222222222222222222222222222222</TxetContent>
                    </OrdInfoTable>
                    <OrdInfoTable>
                        <TxetContent>3333333333333333333333測333333333333333333</TxetContent>
                    </OrdInfoTable>
                    <OrdInfoTable>
                        <TxetContent>4444444測444444444444444444444444444444444</TxetContent>
                    </OrdInfoTable>
                    <OrdInfoTable>
                        <TxetContent>55555555555555555555555555555測55555555555</TxetContent>
                    </OrdInfoTable>
                    <FreeSnTable />
                </GetCardResult>
            </ReturnResult>
        </GetCardResult>
    </GetCardResponse>
</soap:Body>

以下是代码:

HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(url);          
post.setRequestEntity(new StringRequestEntity(xmlRequest.toString()));

post.setRequestHeader("Content-type", "application/soap+xml; charset=utf-8");
post.setRequestHeader("Content-Length", xmlRequest.length()+"");
responseCode = httpClient.executeMethod(post);
InputStream in = post.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
String line;  
String xmlresponse = ""; 
while( ( line = reader.readLine() ) != null ) { 
        xmlresponse = xmlresponse+line;
}  
System.out.println("XML Response:\n");
xmlresponse = xmlresponse.replaceAll("&lt;", "<");
xmlresponse = xmlresponse.replaceAll("&gt;", ">");
System.out.println(xmlresponse+"\n");
// clean everything  
reader.close();
XMLTag xmlTag = XMLDoc.from(xmlresponse, true);
System.out.println("\n" + xmlTag.gotoRoot().gotoChild().gotoChild().gotoTag("GetCardResult/ReturnResult/GetCardResult/PrdInfoTable").getCurrentTagName());
                System.out.println("PrdNote: "+ xmlTag.gotoRoot().gotoChild().gotoChild().getText("GetCardResult/ReturnResult/GetCardResult/PrdInfoTable/PrdNote[1]"));

System.out.println("\n" + xmlTag.gotoRoot().gotoChild().gotoChild().gotoTag("GetCardResult/ReturnResult/GetCardResult/PrdInfoTable").getCurrentTagName());
System.out.println("PrdNote: "+ xmlTag.gotoRoot().gotoChild().gotoChild().getText("GetCardResult/ReturnResult/GetCardResult/PrdInfoTable/PrdNote[2]"));

1 个答案:

答案 0 :(得分:0)

实现此目标的另一种简单方法是使用XPath表达式。

此代码读取xml文件(使用您的XML代码测试),查找PrdNote和TxetContent元素。方法extractNodesValues返回ArrayList<String>及其值:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Test{

    public static void main(String[] args){
         try {
             File myXmlFile = new File("src/test.xml");
             String xpath_PrdNotes = "/Envelope/Body/GetCardResponse/GetCardResult/ReturnResult/GetCardResult/PrdInfoTable/PrdNote/text()";
             String xpath_TxetContent = "/Envelope/Body/GetCardResponse/GetCardResult/ReturnResult/GetCardResult/OrdInfoTable/TxetContent/text()";

             ArrayList<String> prdNotesValues = extractNodesValues(myXmlFile, xpath_PrdNotes );
             ArrayList<String> txetContentValues = extractNodesValues(myXmlFile, xpath_TxetContent );

             System.out.println("PrdNotesValues:");
             for(String val : prdNotesValues){                   
                 System.out.println(val);
             }
             System.out.println("");
             System.out.println("TxetContentValues:");               
             for(String val : txetContentValues){                    
                 System.out.println(val);
             }               
         }

         catch(XPathExpressionException e){ System.out.println(e.getMessage()); }
         catch(IOException e){ System.out.println(e.getMessage()); }
         catch(SAXException e){ System.out.println(e.getMessage()); }
         catch(ParserConfigurationException e){ System.out.println(e.getMessage()); }
   }

   public static ArrayList<String> extractNodesValues(File f, String xpath_expression) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException  {      
        Document xmlDocument;       
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();         
        DocumentBuilder builder;
        XPath xPath;
        NodeList nodeList;        
        Node n; 
        ArrayList<String> result;

        builder = builderFactory.newDocumentBuilder();
        xmlDocument = builder.parse(f);              
        xPath =  XPathFactory.newInstance().newXPath();                                  
        result = new ArrayList<String>();

        // here all values from PrdNote elements are stored
        nodeList = (NodeList)xPath.compile(xpath_expression).evaluate(xmlDocument, XPathConstants.NODESET);        

        if(nodeList != null && nodeList.getLength() > 0) {
            //iterate over all obtained nodes matching the xpath expression
            for(int i=0; i<nodeList.getLength(); i++){                  
                result.add(nodeList.item(i).getNodeValue());
            }               
        }           
        return result;
    } 
}

<强>输出:

PrdNotesValues:
* 測12346666666666666666666666666666666
* 測56787777777777777777777
* 測12345611111111111111111

TxetContentValues:
測1111111111111111111111111111111111111111
22222測22222222222222222222222222222222222
3333333333333333333333測333333333333333333
4444444測444444444444444444444444444444444
55555555555555555555555555555測55555555555

希望这有帮助。