0

I have an XML document, that looks like this (I know, it doesn't make sense, it's just an example):

<Person>
  <Name>Peter</Name>
  <Country>Sweden</Country>
  <Param name="Sport" value="yes"/>
  <Param name="Color" value="no"/>
<Person/>

It can have an infinit number of the element Param.
Getting the content of Country I do

String country = doc.getElementsByTagName("Country").item(0).getTextContent();

Getting the content of the first attribute name of the first Param I do

String name = source.getElementsByTagName("Param").item(0).getAttributes().item(0).getNodeValue();

But how can I get all values of all the attributes of Param, without knowing how many elements of Param exist?

I need something like ("pseudo code"):

HashMap<String, String> hm = new HashMap<String, String>();

for(int i=0; i<=source.getElementsByTagName("Param").size(); i++){
  String name = source.getElementsByTagName("Param").item(i).getAttributes().item(0).getNodeValue();
  String value = source.getElementsByTagName("Param").item(i).getAttributes().item(1).getNodeValue();

  hm.put(name, value);
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

2 Answers2

1

You can ask for an attribute by its name.

String attrName = source.getElementsByTagName("Param").item(i).getAttribute("name"));
String value = source.getElementsByTagName("Param").item(i).getAttribute("value"));
//you could test if the values are null
hm.put(attrName, value);
terrywb
  • 3,740
  • 3
  • 25
  • 50
0
    HashMap<String, String> hm = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    Document document = reader.read("yourxmlfilehere(url, file)");
    root = document.getRootElement();
    root = root.element("Person");
    for(Iterator i = root.elementIterator("Param"); i.hasNext();)
    {
        Element e = (Element)i.next();
        hm.put(e.attributeValue("name"), e.attributeValue("value"));
    }
brso05
  • 13,142
  • 2
  • 21
  • 40