解析包含超链接的xml字符串

时间:2011-08-17 18:02:37

标签: java android xml parsing xml-parsing

我正在使用DOM来解析XML字符串,如下例所示。这在一个实例中很有效。我试图解析的文件看起来像这样:

<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>

我用来解析XML的代码如下:

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

        Document doc = db.parse(is);
        NodeList nlResponse = doc.getElementsByTagName("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++;  

我能够解析代码并将结果放入字符串数组(而不是System.out.println())。使用当前代码,我的字符串数组如下所示:

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

我想要一些方法能够读取“建议”中的其余信息,以便最终在TextView中显示超链接(以及其他输出)。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

我为我之前的答案道歉,假设你的xml格式不正确。

我认为发生的事情是你对getCharacterDataFromElement的调用仅查看文本的第一个子节点,当它需要查看所有子节点并获取href属性以及第二个文本时查看推荐节点时的子节点。

e.g。获得推荐元素后

            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;