Need some advice please. I'm parsing xml and put some data from it to a HashMap. Please, take a look at a piece of code:
final HashMap<String,String> urls = new HashMap<String,String>();
* * *
NodeList nList = doc.getElementsByTagName("Row");
for (int z=0; z<nList.getLength(); z++) {
Node nNode = nList.item(z);
Element eElement = (Element) nNode;
NodeList a = eElement.getElementsByTagName("item");
for (int i=0; i<a.getLength(); i++) {
urls.clear();
String b = eElement.getElementsByTagName("item").item(i).getTextContent();
String c = eElement.getElementsByTagName("url").item(i).getTextContent();
urls.put(b, c);
System.out.println(urls);
}
}
So, I've got this pairs:
{Select product=bla-bla-bla}
{Single Landmine Shirt=/www.sample.com/landmine-single-shirt}
{Women's Silver & Black Bar=/www.sample.com/womens-silver-and-black-bar}
{High Density Foam Rollers=/www.sample.com/high-density-foam-rollers}
Now I 'd like to print key value (Url of product) by key(Product), while I'm selecting a corresponding item from d-down List.
/*comboBox:*/ addProduct.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
String s = String.valueOf(addProduct.getSelectedItem());
if ((e.getStateChange() == ItemEvent.SELECTED) && (urls.containsKey(s))) {
Object v = (String) urls.get(s);
System.out.println("Your url: " + v.toString());
}
}
});
IDK what I'm doing wrong, but when I'm just adding simple Strings to Map: urls.put("Select product", "test Url"); -> All works good. Please advice how to deal with it. Will be glad for any answers
You are aware of the fact that you're clearing your HashMap
on each iteration. This means that your HashMap
will end containing one and only element : the last item
tag's data.
for (int i=0; i<a.getLength(); i++) {
urls.clear();
// ...
}
Get rid of this line and your urls
should be filled correctly.