如何使用DOM解析器解析XML

时间:2013-02-15 07:09:56

标签: android parsing dom xml-parsing

如何使用DOM PARSER

解析以下XML
<Result>
<Status>OK</Status>
<All_BookDetails>
<BookAuthor>Mohammadi Reyshahri</BookAuthor> 
<BookRating>0</BookRating>
<BookDescription>Islamic belief and ideology</BookDescription>
<DatePublished>May  1 1992 12:00AM</DatePublished>
<BookTitle>Are You Free or Slave</BookTitle>
<BookID>171</BookID>
<BookCode>EN171</BookCode>
<BookImage>1.jpg</BookImage>
<TotalPages>164</TotalPages>
</All_BookDetails>
</Result>

我希望获得BookAuthorBookRatingBookDescriptionDatePublishedBookTitleBookID,{{1}的值},BookCode BookImage

我该怎么办?我试图解析上面的XML选择TotalPages作为父节点,但All_BookDetails返回0长度

感谢

1 个答案:

答案 0 :(得分:3)

获取XML DOM元素

public Document getDomElement(String xml) {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setCoalescing(true);
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    } catch (IOException e) {
        return null;
    }

    return doc;

}

然后我尝试了这个并且它的工作

Document doc = parser.getDomElement(XMLString);
            NodeList nl = doc.getElementsByTagName("All_BookDetails");

            progressDialog.setCancelable(true);
            Element e = (Element) nl.item(0);
            BookRating = (Integer.valueOf(parser.getValue(e,
                        "BookAuthor")));

            BookTitle = parser.getValue(e, "BookTitle");
            BookAuthor = parser.getValue(e, "BookAuthor");
            BookPublishDate = parser.getValue(e, "DatePublished");
            BookDescription = parser.getValue(e, "BookDescription");
            bookID = parser.getValue(e, "BookID");
            bookCode = parser.getValue(e, "BookID");
            bookPageCount = parser.getValue(e, "TotalPages");