5

Seems like a basic question but I can't find this anywhere. Basically I've got a list of XML links like so: (all in one string)

I already have the "string" var which contains all the XML. Just extracting the HTML strings.

<?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>

I want to convert these into a arrayList, so something like URLArray[0] would be the first address as a string.

Can anyone tell me how to do this thanks?

Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95

3 Answers3

7
  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()); 
  }
srini.venigalla
  • 5,137
  • 1
  • 18
  • 29
  • What's the personal namespace? I'm getting the error PersonalNamespaceContext cannot be resolved to a type – Oliver Dixon Aug 06 '12 at 21:07
  • that's the xmlns attribute, remove it and try? – srini.venigalla Aug 06 '12 at 21:17
  • Ah it wasn't in my library, I downloaded here: http://code.google.com/p/fabulous/source/browse/branches/3.0/3.0.0/src/org/unisa/fab/PersonalNamespaceContext.java?r=8 Works great, thanks so much you've saved me hours. – Oliver Dixon Aug 06 '12 at 21:18
3

You are right, there should be some other resources out there that can help you. Maybe your searches just do not use the right keywords.

You basically have 2 choices:

  1. Use an XML processing library. SAX, DOM, XPATH, & xmlreader are some keywords you can use to find some.

  2. Just ignore the fact that your string is xml and perform normal string operations on it. splits, iterate through it, regular expressions, ect...

Colin D
  • 5,641
  • 1
  • 23
  • 35
-2

Yes for that you have to perform XML Parsing.

then store that in ArrayList.

ex:

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

aList.add("your string");
MAC
  • 15,799
  • 8
  • 54
  • 95