问题
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