How to get value of node list in xml dom parser?

ぐ巨炮叔叔 提交于 2019-12-24 08:56:14

问题


I have one XML which look like this ::

<Channels>
       <Channel Id="511" Title="Test" ChannelDescription="This is Test Channel./>
</Channels>

I am successfully parse this kind of XML.My Problem is that when i fired the webservice and if there is no authentication from the server then the webservice response like this::

<AuthenticationError>An Active Session Already Exists For This User.</AuthenticationError>

So how can i check that root node is "Authentication Error" or "Notes". And if i get the Authentication Error tag then how can i get its node value which is "An Active Session Already Exists For This User."??

Code for XML Parsing is this::

NodeList node =null;
node= (NodeList)result.getElementsByTagName("Channels");


for(int j=0;j<node.getLength();j++)
{                             
Node aNode=node.item(j);  
Element fstElmnt = (Element) aNode;

NodeList websiteList = fstElmnt.getElementsByTagName("Channel");
int check=websiteList.getLength();

for(int k=0;k<check;k++)
{
    DatabaseConstant myChannels = new DatabaseConstant();
    Node checkNode=websiteList.item(k);

    Element websiteElement = (Element) checkNode;                                                                               
    myChannels.id=websiteElement.getAttribute("Id");
    myChannels.title=websiteElement.getAttribute("Title");

    channel .add(myChannels);
    }
}
}

I hope my question is clear... Please provide the solution asap. Thanks in Advance....


回答1:


Use getDocumentElement() to get root Element, then use getTagName() to get tag name.

Example:

    Element root = result.getDocumentElement();
    String name = root.getTagName();

    if(name.equalsIgnoreCase("AuthenticationError") )
    {
        String value = myDocument.getDocumentElement().getTextContent();
        System.out.println("Error:" + value);
    }
    else if(name.equalsIgnoreCase("Notes") )
    {
       NodeList nodes = root.getElementsByTagName("Channels");

       for(int i = 0 ; i < nodes.getLength() ; i ++)
       {
           //-----do something with channels nodes--
       }
    }


来源:https://stackoverflow.com/questions/12119356/how-to-get-value-of-node-list-in-xml-dom-parser

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