using java dom to update file
I've the following code and this html file. I'm trying to locate the <head> tag and add text in between it, however it isn't working. Could someone please take a look at my code and tell me what is missing? Thanks.
<xml version="1.0" encoding="UTF-8"?/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"/>
<meta http-equiv="Content-Style-Type" content="text/css"/>
<title>a title</title>
</head>
<body>
<p>some text</p>
</body>
</html>
Code:
ocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("test.html"));
String newinfo = "text to be added";
Element root = doc.getDocumentElement();
NodeList rootlist = root.getChildNodes();
for(int i=0; i<rootlist.getLength(); i++)
{
Element head = (Element)rootlist.item(i);
NodeList namelist = head.getChildNodes();
Text headtext = (Text)namelist.item(0);
String oldname = headtext.getData();
if(oldname.equals(newinfo))
{
Element head2 = (Element)namelist.item(1);
NodeList namelist2 = head.getChildNodes();
Text headtext2 = (Text)namelist.item(0);
headtext.setData(newinfo);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}