1

我编写了这段代码来解析XML字符串,但它不起作用。没有错误,但没有给出任何输出。

我的 XML 字符串:

String xml = "<ArrayOfString>" + "<string>{" + "categoryId"+":1," +
    "Title" +":"+"Rock"+"," + "songs" +":" +" null}</string>" + "</ArrayOfString>";

编码:

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(xml);
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("ArrayOfString");

        item = new TextView[nodeList.getLength()];
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            item[i] = new TextView(this);

            Element fstElmnt = (Element) node;
            NodeList itemList = fstElmnt.getElementsByTagName("string");
            Element itemElement = (Element) itemList.item(0);
            itemList = itemElement.getChildNodes();
            item[i].setText("item = "
                            + ((Node) itemList.item(0)).getNodeValue());

            layout.addView(item[i]);
        }
    }
    catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
    }

    /** Set the layout view to display */
    setContentView(layout);
}
4

1 回答 1

1

问题是您调用DocumentBuilder.parse(String)的目的是接受 URL 作为其参数,而不是实际的 XML。

最简单的替代方法可能是使用InputSource来自 a 的读数StringReader

StringReader reader = new StringReader(xml);
InputSource source = new InputSource(reader);
Document doc = db.parse(source);
于 2013-08-18T13:25:03.443 回答