Thursday, 17 October 2013

Getting Xml Tag Values using Stack in Java (Applicable to HTML tags) - Parsing



Method Functionality
  •  This method is used to parse the given XML / HTML Entry containing tags.
  •  The values inside the tags are pushed into the Stack.
  •  You can retrieve the values later from the stack by knowing the depth of the Element
Input
<student>
         <name>Nijin</name>
         <college>SSN</college>
         <city>Chennai</city>
</student>

Output
[Nijin, SSN,Chennai]

Program
public String getValueFromXmlKey(String xmlEntry, int pos){
String value= null;
boolean tagDetected = false;

Stack<String> stack = new Stack<String>();

//Converting String to char Array
char[] xmlEntryArray = xmlEntry.toCharArray();

String elements = "";
for(char c:xmlEntryArray){
if(tagDetected==false){
if(c=='<'){ //Searching for opening tag
tagDetected = true;
if(elements!=""){
stack.push(elements);
}
elements = "";
}
else{
elements += c;
}
}
else{
if(c=='>'){ //Searching for closing tag
tagDetected = false;
}
}
}
System.out.println(stack.get(pos));
return stack.get(pos);
}

No comments:

Post a Comment