开发者

Parsing xml string containing hyperlink

I am using DOM to parse an XML string as in the following example. This works great except in one instance. The document which I am trying to parse looks like this:

<response requestID=\"1234\">
    <expectedValue>Alarm</expectedValue>
    <recommendations>For steps on how to resolve visit <a href=\"some website\">Website</a> and use the search features for \"Alarm\"<recommendations>
    <setting>Active</setting>
<response>

The code I used to parse the XML is as follows:

try {   
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xmlResult));

        Document doc = db.parse(is);
        NodeList nlResponse = doc.getElemen开发者_如何学GotsByTagName("response");

        String[] String = new String[3];  //result entries

        for (int i = 0; i < nlResponse.getLength(); i++) {
            Element e = (Element) nlResponse.item(i);
            int c1 = 0; //count for string array

            NodeList ev = e.getElementsByTagName("expectedValue");
            Element line = (Element) ev.item(0);
            String[c1] = (getCharacterDataFromElement(line));
            c1++;

            NodeList rec = e.getElementsByTagName("recommendations");
            line = (Element) rec.item(0);
            String[c1] = (getCharacterDataFromElement(line));
            c1++;

            NodeList set = e.getElementsByTagName("settings");
            line = (Element) set.item(0);
            String[c1] = (getCharacterDataFromElement(line));
            c1++;  

I am able to parse the code and put the result into a string array (as opposed to the System.out.println()). With the current code, my string array looks as follows:

String[0] = "Alarm"
String[1] = "For steps on how to resolve visit"
String[2] = "Active"

I would like some way of being able to read the rest of the information within "Recommendations" in order to ultimately display the hyperlink (along with other output) in a TextView. How can I do this?


I apologize for my previous answer in assuming your xml was ill-formed.

I think what is happening is that your call to the getCharacterDataFromElement is only looking at the first child node for text, when it will need to look at all the child nodes and getting the href attribute as well as the text for the 2nd child node when looking at the recommendations node.

e.g. after getting the Element for recommendation

            String srec = "";
            NodeList nl = line.getChildNodes();
            srec += nl.item(0).getTextContent();

            Node n = nl.item(1);
            NamedNodeMap nm = n.getAttributes();
            srec += "<a href=\"" + nm.getNamedItem("href").getTextContent() +  "\">" + n.getTextContent() + "</a>";

            srec += nl.item(2).getTextContent();

            String[c1] = srec; 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜