开发者

Parsing XML in Java

i have response structure that i want to parse in Java. Can anyone help me with this?

    <message_response xmlns="">
      <action name="GETCIL">
        <param name="bookingNote" value="" require="" read-only=""><![CDATA[bookingNote]]></param>
        <param name="CarrierLinkType" value="" require="" read-only=""><![CDATA[True]]></param>
        <param name="Carrier" value="" require="" read-only=""><![CDATA[SK185]]></para开发者_Python百科m>

 <param_list name="ViaAddressList" id="GETCIL">
      <value>
        <param_list name="ViaAddressId" id="ViaAddressList">
          <value><![CDATA[877765050_5511]]></value>
        </param_list>
        <param_list name="AddressDate" id="ViaAddressList">
          <value><![CDATA[10/12/2010]]></value>
        </param_list>
        <param_list name="AddressTime" id="ViaAddressList">
          <value><![CDATA[12:12]]></value>
        </param_list>
      </value>
    </param_list>


</action>
    </message_response>


The easiest way to extract specific values from an XML document (as opposed to parsing the complete document with SAX) is to use XPath as follows:

//1. load the document into memory.
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

//2. Create an XPath.
XPath xpath = XPathFactory.newInstance().newXPath();

//3. Evaluate the xpath expression.
String actionName = xpath.evaluate("/message_response/action/@name", documentBuilder.parse(xmlFile));

There's not much more to it other than the XPath.evaluate method is overloaded in order to allow nodes and node lists to be returned (see javax.xml.xpath.XPathConstants for the types).

Then you just need to read-up on the xpath syntax (http://www.w3schools.com/xpath/xpath_syntax.asp).


Why the CDATA sections around the data?

You can use SAX or DOM to parse XML.

There are also libraries wrapping SAX and DOM parsers that make your life easier for common tasks. Two that come to mind for Java are JDOM and DOM4J. Google for them - there are tutorials and examples available that will show you what you need to know.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜