bearhunterUA
bearhunterUA

Reputation: 259

Parse xml without tagname

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

Upvotes: 4

Views: 3902

Answers (1)

ug_
ug_

Reputation: 11440

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

Upvotes: 5

Related Questions