用于简单XML节点字符串的Android XML解析器或库

时间:2011-03-26 22:04:02

标签: android xml parsing

这是XML文件的一个例子:

  <?xml version="1.0"?>
  <catalog>
    <book id="bk101">
     <author>Gambardella, Matthew</author>
     <title>XML Developer's Guide</title>
     <genre>Computer</genre>
     <price>44.95</price>
     <publish_date>2000-10-01</publish_date>
     <description>An in-depth look at creating applications 
      with XML.</description>
    </book>

    <book id="bk102">
     <author>Ralls, Kim</author>
     <title>Midnight Rain</title>
     <genre>Fantasy</genre>
     <price>5.95</price>
     <publish_date>2000-12-16</publish_date>
     <description>A former architect battles corporate zombies, 
      an evil sorceress.</description>
    </book>

    <book id="bk103">
     <author>Corets, Eva</author>
     <title>Maeve Ascendant</title>
     <genre>Fantasy</genre>
     <price>5.95</price>
     <publish_date>2000-11-17</publish_date>
     <description>After the collapse of a nanotechnology 
      society in England.</description>
     </book>
  </catalog>

我想通过许多标准书籍在这个文件中搜索,例如作者,按流派,价格等...

我将使用XPath查询来执行此操作,因此有一些简单的方法可以使用??? 例如,我想检查一个作者是否存在,为了做到这一点,我必须有一个方法,我将通过一个XPath查询来转结结果......

提前致谢,

致以最诚挚的问候,

阿里

1 个答案:

答案 0 :(得分:3)

您可以将DOM API与javax.xml.xpath.XPathFactoryjavax.xml.xpath.XPath结合使用,如http://developer.android.com/reference/javax/xml/xpath/package-summary.html所述。

例如:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();;
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse("input.xml");

// NodeList books = document.getElementsByTagName("book");

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/catalog/book[1]/author"; // first book
Node author = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);

if (author == null)
    System.out.println("Element author not exists");
else
    System.out.println(author.getTextContent());