Android XML Parser or Library for Simple XML Node Strings

前端 未结 1 1549
执笔经年
执笔经年 2021-01-07 07:53

This an example of XML file:

  
  
    
     Gambardella, Matthew         


        
1条回答
  •  借酒劲吻你
    2021-01-07 08:52

    You can combine DOM API with javax.xml.xpath.XPathFactory and javax.xml.xpath.XPath as descibed at http://developer.android.com/reference/javax/xml/xpath/package-summary.html.

    For example:

    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());
    

    0 讨论(0)
提交回复
热议问题