Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Get the list or name of all attributes in a XML element

Tags:

java

dom

xml

xpath

i have an xml element

   <base baseAtt1="aaa" baseAtt2="tt">
        <innerElement att1="one" att2="two" att3="bazinga"/>
   </base>

and i would like to get the list of attributes. for both the base element and the inner element.

i dont know the name of the innerElement it can have many different names.

 NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
 Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

the goal is to get a kind of dictionary as output,

for example for the xml above the output will be a dictionary with those valuse.

baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

i am using jre 1.5

like image 710
yossi Avatar asked Dec 09 '22 07:12

yossi


1 Answers

Here is plain DOM based solution (however there is nothing wrong to combine XPath with DOM in Java):

NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

NamedNodeMap baseElmnt_gold_attr = baseElmnt_gold.getAttributes();
for (int i = 0; i < baseElmnt_gold_attr.getLength(); ++i)
{
    Node attr = baseElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

NodeList innerElmntLst_gold = baseElmnt_gold.getChildNodes();
Element innerElement_gold = null;
for (int i = 0; i < innerElmntLst_gold.getLength(); ++i)
{
    if (innerElmntLst_gold.item(i) instanceof Element)
    {
        innerElement_gold = (Element) innerElmntLst_gold.item(i);
        break; // just get first child
    }
}

NamedNodeMap innerElmnt_gold_attr = innerElement_gold.getAttributes();
for (int i = 0; i < innerElmnt_gold_attr.getLength(); ++i)
{
    Node attr = innerElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

Result:

baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"
like image 138
Grzegorz Szpetkowski Avatar answered Jan 01 '23 10:01

Grzegorz Szpetkowski