Parse xml without tagname

瘦欲@ 提交于 2019-12-22 08:44:24

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/24446849/parse-xml-without-tagname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!