answered
2013-05-29 18:57:24 +0800
jatindersingh 93 ● 5
http://javaj2eehub.com/
If you are saving the HTML code for select box in DB then you can use the below code to parse the HTML code and save its value and name either in Model or in hashtable,later you can use to populate the combobox model.
import java.io.IOException;
import java.io.StringReader;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class MyTest
{
public static void main(String as[])
{
String strXml="<Select name='122'><option value='12'>Cheque</option><option value='12'>Cash</option></Select>";
try
{
Document doc=loadXMLFromString(strXml);
doc.normalize();
NodeList nList=doc.getElementsByTagName("Select");
Hashtable<String, String> selectBox=new Hashtable<String,String>();
for(int i=0;i<nList.getLength();i++)
{
Node rootN=nList.item(i);
if(rootN!=null && rootN.getNodeType()==Node.ELEMENT_NODE)
{
Element rootE=(Element)rootN;
NodeList dataList=rootE.getElementsByTagName("option");
for(int j=0;j<dataList.getLength();j++)
{
String strName=null;
String strValue=null;
if(dataList!=null)
{
Node rootNode=dataList.item(j);
Element el = (Element)rootNode;
if(el.getFirstChild()!=null)
{
strName=el.getFirstChild().getNodeValue();
}
strValue=getAttribute(rootNode);
if(strValue!=null && strValue.length()>0 && strName!=null && strName.length()>0)
{
selectBox.put(strName, strValue);
}
else
{
selectBox.put(strName, strName);
}
}
}
}
}
}
catch(Exception e)
{
}
}
private static String getAttribute(Node node)
{
String lookupName="";
Element child = (Element) node;
lookupName=child.getAttribute("value");
return lookupName;
}
private static Document loadXMLFromString(String xml) throws Exception
{
Document doc=null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
doc=builder.parse(is);
}
catch(ParserConfigurationException pce)
{
throw pce;
}
catch(IOException io)
{
throw io;
}
catch(SAXException saxe)
{
throw saxe;
}
catch(Exception e)
{
throw e;
}
return doc;
}
}