Results 1 to 7 of 7
  1. #1
    newbieal is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default 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>

    Java 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();
                }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    If you'll post code that compiles and executes, it'd be easier to test.

    Also show the type of data you want to add. Is it HTML with special chars or just text?
    Last edited by Norm; 10-09-2008 at 07:55 PM.

  3. #3
    newbieal is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    It is just text that should be added between the <head> tags. i'll keep trying to work on the code to make it compile but in the meanwhile any ideas why it isn't would be greatly appreciated.

  4. #4
    newbieal is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default updated code

    This is what I have so far, it compiles but does not accomplish what I need it to:

    Java Code:
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	    try
    	    {
    		DocumentBuilder db = dbf.newDocumentBuilder();
    	    Document doc = db.parse(new File("testing.html"));
    	    String newinfo = "text to be added";
    
    		Element root = doc.getDocumentElement();
    	    NodeList rootlist = root.getChildNodes();
    	    
    	   Node current = null;
    	   int count = rootlist.getLength();
    	   for (int i = 0; i < count; i++)
    	   {
    		   current = rootlist.item(i);
    		   if(current.getNodeType() == Node.ELEMENT_NODE)
    		   {
    			   Element element = (Element)current;
    			   NodeList children = element.getChildNodes();
                   if(element.getTagName().equalsIgnoreCase("head"))
    			   {
    				   Text headtext = (Text)children.item(0);
                       headtext.setData(newinfo);
    
    			   }
    			   
    		   }
    		   System.out.println(doc.getDocumentElement());
    		   
    	   }
    	    }
    	    catch (Exception e)
    	    {
    	    	e.printStackTrace();
    	    }

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    If you'll post code that compiles and executes, it'd be easier to test.
    That would include everything from import to ending }
    it compiles
    You have a better compiler than mine then.

  6. #6
    newbieal is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default complete code

    Java Code:
    import java.io.File;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    
    import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
    
    
    // using DOM
    public class testingWriteToHTML {
    	
    	public static void main(String[] args) {
    
    		
    	    try
    	    {
    	    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			dbf.setValidating(false);
    			dbf.setNamespaceAware(false);
    			dbf.setExpandEntityReferences(false);
    			
    	    	DocumentBuilder db = dbf.newDocumentBuilder ( );
    	    	
    	        Document doc = db.parse ( new File ( "test2.html" ) );
    	   
    	        String newinfo = "some text";
    	   
    	        Element root = doc.getDocumentElement ( );
    	        // NodeList list = doc.getElementsByTagName ( "head" );
    	        System.out.println ( root.getNodeName ( ) );
    	        NodeList list = root.getChildNodes ( );
    	        StringBuffer sb = new StringBuffer();
    	         for ( int i = 0; i < list.getLength ( ); i++ ) 
    	        {
    	          if ( list.item ( i ).getNodeName ( ).equals ( "head" ) ) 
    	          {
    	        	  list.item ( i ).setTextContent ( newinfo );
    	            
    	          }
    	        }
    	        XMLSerializer serializer = new XMLSerializer ( );
    	        serializer.setOutputCharStream ( new java.io.FileWriter ( "test2.html" ) );
    	        serializer.serialize ( doc );
    
    	    }
    	    catch (Exception e)
    	    {
    	    	e.printStackTrace();
    	    }
    
    	}
    }

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    I'm not sure that this is the way to go. Your app is supposed to insert some text/HTML between the <HEAD> and </HEAD> tags.
    XML is much more precise/regulated than HTML. I would think you'd find HTML pages that would fail the XML parsing.

    I'd vote for doing the scanning your self with indexOf() etc to find the <HEAD> tag and add your stuff and then copy the rest of the HTML page to output.

    Comment on your code:
    Don't use the same name for the input and output files.
    For testing add a couple of String definitions at the head of the code:
    final static String inFile = "test2In.html"; // Input file
    final static String outfile = "test2Out.html"; // output file

    It makes it easier to see what files are involved and to change them during your testing.

Similar Threads

  1. [SOLVED] Update an XML file
    By Eranga in forum Advanced Java
    Replies: 4
    Last Post: 07-15-2008, 02:03 PM
  2. can i update the tag value of XMl file by other value(string
    By pankaj_salwan in forum Advanced Java
    Replies: 7
    Last Post: 07-04-2008, 08:12 AM
  3. Update a record in Random access file
    By Rgfirefly24 in forum New To Java
    Replies: 2
    Last Post: 04-24-2008, 10:07 PM
  4. Java Update Installation
    By guest in forum New To Java
    Replies: 1
    Last Post: 12-01-2007, 04:36 AM
  5. Java Crashes on Mac 10.3.9 not sure how to update
    By patricknowow in forum New To Java
    Replies: 1
    Last Post: 11-30-2007, 03:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •