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);
}
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);