使用Java在XML中读取XML

时间:2013-07-10 05:22:05

标签: java xml

如何阅读XML< returnMsg>成功< / returnMsg> java中此标记的值? 如何在此示例中读取标记的数据。 我得到了不允许处理指令匹配“[xX] [mM] [lL]”。得到例外

     <?xml version="1.0" encoding="utf-8"?>
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <soapenv:Body>
                    <doServiceResponse xmlns="http://ocs.ztesoft.com">
                        <doServiceReturn>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;zsmart&gt;

  &lt;Data&gt;
    &lt;header&gt;
      &lt;returnMsg&gt;Successful&lt;/returnMsg&gt;
      &lt;ACTION_ID&gt;ModifyBalReturnAllBal&lt;/ACTION_ID&gt;
      &lt;REQUEST_ID&gt;0032013070900000503&lt;/REQUEST_ID&gt;
      &lt;returnCode&gt;0&lt;/returnCode&gt;
    &lt;/header&gt;
    &lt;body&gt;


      &lt;TransactionSN&gt;503&lt;/TransactionSN&gt;
    &lt;/body&gt;
  &lt;/Data&gt;
&lt;/zsmart&gt;
            </doServiceReturn></doServiceResponse></soapenv:Body></soapenv:Envelope>

JAVA CODE

dbf = DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();

            is = new InputSource();
            is.setCharacterStream(new StringReader(respString));
            doc = db.parse(is);
            nodes = doc.getElementsByTagName("soapenv:Envelope");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);



                NodeList txnStatus = element.getElementsByTagName("returnCode");
                Element line = (Element) txnStatus.item(0);
                bean.setTxnStatus(getCharacterDataFromElement(line));



                NodeList message = element.getElementsByTagName("returnMsg");
                line = (Element) message.item(0);
                bean.setMessage(getCharacterDataFromElement(line));
            }

异常

org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

1 个答案:

答案 0 :(得分:1)

XML文件转换为JAVA OBJECT的方法有很多种。 SAXJAXB算法是其中两种。 JAXB算法更易于使用。我更喜欢使用JAXB。 HERE是帮助您从XML文件创建对象的链接。 享受它...

http://www.mkyong.com/java/jaxb-hello-world-example/