2012-08-06 134 views
2

看起来像一个基本问题,但我无法在任何地方找到它。基本上我有这样的XML链接列表:(全部在一个字符串中)将XML字符串转换为ArrayList

我已经有了包含所有XML的“string”var。只是提取HTML字符串。

<?xml version="1.0" encoding="UTF-8"?> 
<fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true"> 
<photo> 
    <src_small>http://photos-a.ak.fbcdn.net/hphotos-ak-ash4/486603_10151153207000351_1200565882_t.jpg</src_small> 
</photo> 
<photo> 
    <src_small>http://photos-c.ak.fbcdn.net/hphotos-ak-ash3/578919_10150988289678715_1110488833_t.jpg</src_small> 
</photo> 

我想将这些转换为ArrayList中,所以像URLArray [0]将是第一个地址为一个字符串。

谁能告诉我如何做到这一点,谢谢?

+2

使用一个XMLReader来解析XML,在分析过程中构建出你的ArrayList。 – CSmith 2012-08-06 17:32:54

+0

这个问题http://stackoverflow.com/questions/3625506/what-is-the-best-way-to-handling-xml-in-android有一些很好的XML解析器的选择。 – Vikdor 2012-08-06 17:34:32

+0

对于那些应该是一项简单任务的许多代码的方法? – 2012-08-06 17:56:40

回答

4
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    InputSource is = new InputSource(new StringReader(xmlString)); 
    Document doc = builder.parse(is); 

    XPathFactory factory = XPathFactory.newInstance(); 
    XPath xpath = factory.newXPath(); 
    xpath.setNamespaceContext(new PersonalNamespaceContext()); 
    XPathExpression expr = xpath.compile("//src_small/text()"); 

    Object result = expr.evaluate(doc, XPathConstants.NODESET); 
    NodeList nodes = (NodeList) result; 
    List<String> urls = new ArrayList<String>(); 
    for (int i = 0; i < nodes.getLength(); i++) { 
     urls.add (nodes.item(i).getNodeValue()); 
     System.out.println(nodes.item(i).getNodeValue()); 
    } 
+0

我在哪里设置字符串? – 2012-08-06 17:43:34

+0

@Oly我更新了答案,请检查 – 2012-08-06 20:44:50

+0

什么是个人名字空间?我收到错误PersonalNamespaceContext无法解析为类型 – 2012-08-06 21:07:18

3

你是对的,应该有一些其他资源可以帮助你。也许你的搜索只是不使用正确的关键字。

你基本上有两个选择:

  1. 使用XML处理库。 SAX,DOM,XPATH,& xmlreader是一些可用于查找某些关键字的关键字。

  2. 只是忽略了你的字符串是xml并对其执行正常字符串操作的事实。分裂,遍历它,正则表达式,等...

-2

是的,因为你必须执行XML Parsing

然后将其存储在ArrayList中。

例如:

ArrayList<String> aList = new ArrayList<String>(); 

aList.add("your string");