4

I have a xml file

<Response>
<StatusCode>0</StatusCode>
<StatusDetail>OK</StatusDetail>
<AccountInfo> 
    <element1>value</element1>
    <element2>value</element2>
    <element3>value</element2>
    <elementN>value</elementN>   
</AccountInfo>
</Response>

And I want parse my elements in AccountInfo, but I dont know elements tag names.

Now Im using and have this code for tests, but in future I will recieve more elemenets in AccountInfo and I dont know how many or there names

String name="";
String balance="";
 Node accountInfo = document.getElementsByTagName("AccountInfo").item(0);

        if (accountInfo.getNodeType() == Node.ELEMENT_NODE){
            Element accountInfoElement = (Element) accountInfo;
            name = accountInfoElement.getElementsByTagName("Name").item(0).getTextContent();
            balance = accountInfoElement.getElementsByTagName("Balance").item(0).getTextContent();
        }
bearhunterUA
  • 259
  • 5
  • 15
  • How do you want to extract information in a meaningful way if you don't know what tags there can be (and what they signify)? – Thilo Jun 27 '14 at 08:05
  • Are you sure you would like that dynamically? If you have n number of different variables parsed in a dynamic way, it could be hard to use them (for instance if you use some algorithm to calculate some value). The values would (more or less) be represented in a list. The usual way to do it is have one implementation for a specific set of input. Or would you just like to dump the values to a database? – Pphoenix Jun 27 '14 at 08:06
  • [This answer](http://stackoverflow.com/a/3327264/391161) may get you started. – merlin2011 Jun 27 '14 at 08:07
  • 2
    I want send this info to other module and this module can print it on frontend. My programm will work with different providers and they have different info... list of providers is very large... more then 300 – bearhunterUA Jun 27 '14 at 08:11

1 Answers1

5

Heres 2 ways you can do it:

Node accountInfo = document.getElementsByTagName("AccountInfo").item(0);
NodeList children = accountInfo.getChildNodes();

or you can do

XPath xPath = XPathFactory.newInstance().newXPath();
NodeList children = (NodeList) xPath.evaluate("//AccountInfo/*", document.getDocumentElement(), XPathConstants.NODESET);

Once you have your NodeList you can loop through them.

for(int i=0;i<children.getLength();i++) {
    if(children.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element elem = (Element)children.item(i);
        // If your document is namespace aware use localName
        String localName = elem.getLocalName();
        // Tag name returns the localName and the namespace prefix
        String tagName= elem.getTagName();
        // do stuff with the children
    }
}
ug_
  • 11,267
  • 2
  • 35
  • 52