Zapis elementów strony do XML

0

Witam,

Mam problem z javą. Próbuje zapisać stronę www do własnego pliku XML. Elementy strony wyświetlają mi się w konsoli lecz nie potrafię ich zapisać. Nie wiem jak napisać w klasie main aby odwołać się do klasy TagReplacer i jej funkcji handleText. Rozumiem że jest to banalne ale początki zawsze są ciężkie... Bardzo prosiłbym o pomoc.

Pozdrawiam

Kod główny main

 

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.File;
import javax.xml.parsers.*;
import org.jdom.Attribute;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.swing.text.html.HTMLEditorKit;

public class main {

	public static void main(String[] args) {

		ParserGetter kit = new ParserGetter();
		
		HTMLEditorKit.Parser parser = kit.getParser();
		try {
			URL u = new URL("http://onet.pl");
			DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
		    DocumentBuilder builder = bf.newDocumentBuilder();
			
		    Document myDoc = builder.newDocument();			
			Element myTitle = myDoc.createElement("title");  	    
		    myDoc.appendChild(myTitle);
		    
		    HTMLEditorKit.ParserCallback callback = new TagReplacer(myDoc);
			InputStream in = new BufferedInputStream(u.openStream());
			InputStreamReader r = new InputStreamReader(in);
			parser.parse(r, callback, true);
			   		    
		    Text myText = myDoc.createTextNode("Nazwa tytułu:");
		    myTitle.appendChild(myText);
		    
		    Source source = new DOMSource(myDoc);
		    Result result = new StreamResult(new File("test.xml"));
		    Transformer xformer = TransformerFactory.newInstance().newTransformer();
		    xformer.transform(source, result);
		} 
		catch (MalformedURLException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		} 
		catch (ParserConfigurationException e) {
			e.printStackTrace();
		} 
		catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} 
		catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} 
		catch (TransformerException e) {			
			e.printStackTrace();
		}
	}

	}


Klasa ParserGetter

 
import javax.swing.text.html.*;
public class ParserGetter extends HTMLEditorKit
{
  public HTMLEditorKit.Parser getParser( )
  {
    return super.getParser( );
  }
}

Klasa TagReplacer

 

import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import java.io.*;
import java.net.*;
import java.util.*;

public class TagReplacer extends HTMLEditorKit.ParserCallback {
	boolean czytamTytul = false;
	boolean czytamLink = false;
		
	public TagReplacer() {	
	
	}

	public void handleText(char[] text, int position) {
		if(czytamLink == true){
			System.out.println("Odsyłacz: "+ String.valueOf(text));	
						
		}
		
		if(czytamTytul == true){
			System.out.println("Tytuł: "+ String.valueOf(text));
			Text myText = myDoc.createTextNode("Nazwa tytułu:");
		}
	}
		
  public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int position)
  {
	  if(tag == HTML.Tag.A)
	    {
	    	czytamLink = true;	  	  	
	    	Enumeration e = attributes.getAttributeNames( );
			while (e.hasMoreElements( ))
			{
			    Object name = e.nextElement( );
			    String value = (String) attributes.getAttribute(name);
			    if(name==HTML.Attribute.HREF){
			    System.out.println("HREF = " + value);
			    }
			}
	    	
	    }
	  if(tag == HTML.Tag.TITLE)
	    {
	    	czytamTytul = true;	  	
	    	Enumeration e = attributes.getAttributeNames( );
			while (e.hasMoreElements( ))
			{
			    Object name = e.nextElement( );
			    String value = (String) attributes.getAttribute(name);
			    if(name==HTML.Attribute.TITLE){
			    System.out.println("TITLE = " + value);
			    }
			}	  
	    }
  }

  public void handleEndTag(HTML.Tag tag, int position)
  {
	  if(tag == HTML.Tag.A)
	    {
	    	czytamLink = false;	  	  	
	    	
	    }
	  if(tag == HTML.Tag.TITLE)
	    {
	    	czytamTytul = false;	  	  	
	    
	    }
  }

	}
		
0

Nikt nie podpowie?

0

Z zapisem do xml tego co wyświetlasz w konsoli mysle ze dasz sobie rade. Jakbym wiedział jak to ma być to by Ci napisal ale nie wiem. Nie znam javy ale podobna jest do c# wiec mysle ze dasz rade. Ja tez zmagam sie z zapisem do pliku xml i odczytem. Polecam Ci obejrzeć sobie jakies filmiki na yt po angielsku. Z javy pewnie bedzie tego jeszcze więcej niz z C# ja obejrzałem kilka filmików i zaczynalo cos wychodzić. Próbuj na początek na jakimś prostym programie potem zwiekszaj sobie stopień trudności dodając kolejne klasy a na koniec ogarniesz to. Może nie profi ale bedzie działać. Wiem ze pewnie nic nie pomoglem ale probuj

0

Witam,

Mam problem... A dokładnie z użyciem appendChild. Zapisywanie do XML tytułu ze strony chodzi jak najbardziej... Natomiast linków już jest tutaj problem. A napisałem podobną komendę jak do tytułu. Błąd jaki mi wyskakuje zamieszczam poniżej. Po usunięciu komendy myDoc.appendChild(myLink); błąd nie wyskakuje. Dlaczego tak się dzieje??? Jak naprawić ten problem?

org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. 
	at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(Unknown Source)
	at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source)
	at lab3.TagReplacer.handleText(TagReplacer.java:34)
	at javax.swing.text.html.parser.DocumentParser.handleText(Unknown Source)
	at javax.swing.text.html.parser.Parser.handleText(Unknown Source)
	at javax.swing.text.html.parser.Parser.endTag(Unknown Source)
	at javax.swing.text.html.parser.Parser.parseTag(Unknown Source)
	at javax.swing.text.html.parser.Parser.parseContent(Unknown Source)
	at javax.swing.text.html.parser.Parser.parse(Unknown Source)
	at javax.swing.text.html.parser.DocumentParser.parse(Unknown Source)
	at javax.swing.text.html.parser.ParserDelegator.parse(Unknown Source)
	at lab3.main.main(main.java:46)
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import java.io.*;
import java.net.*;
import java.util.*;

public class TagReplacer extends HTMLEditorKit.ParserCallback {
	boolean czytamTytul = false;
	boolean czytamLink = false;
	Document myDoc ;	
	Text myText;
	Element myTitle;	
	Element myLink;
	
	public TagReplacer(Document myDoc) {
	this.myDoc = myDoc; 
	
	}

	public void handleText(char[] text, int position) {
		
		if(czytamLink == true){
			System.out.println("Odsyłacz: "+ String.valueOf(text));	
			
			myLink = myDoc.createElement("a");		    
		    myDoc.appendChild(myLink);
		   // myTxt = myDoc.createTextNode("odsyłacz");
		    //myLink.appendChild(myTxt);	
						
		}
		
		if(czytamTytul == true){
			System.out.println("Tytuł: "+ String.valueOf(text));			
			
			
			myTitle = myDoc.createElement("title");  	 			
		        myDoc.appendChild(myTitle);
		        myText = myDoc.createTextNode(String.valueOf(text));
		        myTitle.appendChild(myText);
		    
		}
	}  
  public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int position)
  {
	  if(tag == HTML.Tag.A)
	    {
	    	czytamLink = true;	  	  	
	    	Enumeration e = attributes.getAttributeNames( );
			while (e.hasMoreElements( ))
			{
			    Object name = e.nextElement( );
			    String value = (String) attributes.getAttribute(name);
			    if(name==HTML.Attribute.HREF){
			    //System.out.println("HREF = " + value);
			    }
			}
	    	
	    }
	  if(tag == HTML.Tag.TITLE)
	    {
	    	czytamTytul = true;	  	
	    		  
	    }
  }

  public void handleEndTag(HTML.Tag tag, int position)
  {
	  if(tag == HTML.Tag.A)
	    {
	    	czytamLink = false;	  	  	
	    	
	    }
	  if(tag == HTML.Tag.TITLE)
	    {
	    	czytamTytul = false;	  	  	
	    
	    }
  }
	}
0

No ale ja tworzę element "a" w dokumencie, a nie sam w sobie...
W taki sposób:

			myLink = myDoc.createElement("a");		    
		    myDoc.appendChild(myLink); 

Czyli w taki jaki radzi na tamtej stronie.

0

Pomoże ktoś?

1 użytkowników online, w tym zalogowanych: 0, gości: 1