【问题标题】:Search in XML File with XPath in Android在 Android 中使用 XPath 在 XML 文件中搜索
【发布时间】:2011-07-28 01:06:54
【问题描述】:

我正在android上开发一个应用程序!

好吧,我现在有点冲突,我想执行一个 XPath 查询,但我没有来解决这个问题。

这是我使用的 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>

我该怎么办??

提前致谢!!

【问题讨论】:

    标签: android xml xpath


    【解决方案1】:

    看这个例子:

    import java.io.FileReader;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    
    public class GuestList {
    
      public static void main(String[] args) throws Exception {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        NodeList shows = (NodeList) xPath.evaluate("/schedule/show", 
                new InputSource(new FileReader("tds.xml")), XPathConstants.NODESET);
    
        for (int i = 0; i < shows.getLength(); i++) {
          Element show = (Element) shows.item(i);
          String guestName = xPath.evaluate("guest/name", show);
          String guestCredit = xPath.evaluate("guest/credit", show);
          System.out.println(show.getAttribute("weekday") + ", " + show.getAttribute("date") + " - "
              + guestName + " (" + guestCredit + ")");
        }
      }
    
    }
    

    其余的例子在这里:http://jexp.ru/index.php/Java_Tutorial/XML/XPath

    【讨论】:

    • +1 只是因为有人记得显示导入的命名空间!
    • 如果我有在线托管的XML,我可以解析它,我应该全部阅读
    • 要读取外部 XML 文件,您可以使用 URL 类使用 SAX 打开流。用这一行替换 show NodeList 实例化NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new URL( "http://www.exple.com/file.xml").openStream()), XPathConstants.NODESET);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2023-03-17
    • 2013-05-12
    • 2014-08-30
    相关资源
    最近更新 更多