samples.src.FormFieldSetValues Maven / Gradle / Ivy
Go to download
Jericho HTML Parser is a simple but powerful java library allowing analysis and manipulation of
parts of an HTML document, including some common server-side tags, while reproducing verbatim any
unrecognised or invalid HTML. It also provides high-level HTML form manipulation functions.
import au.id.jericho.lib.html.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class FormFieldSetValues {
public static void main(String[] args) throws Exception {
String sourceUrlString="data/form.html";
if (args.length==0)
System.err.println("Using default argument of \""+sourceUrlString+'"');
else
sourceUrlString=args[0];
if (sourceUrlString.indexOf(':')==-1) sourceUrlString="file:"+sourceUrlString;
URL sourceUrl=new URL(sourceUrlString);
String htmlText=Util.getString(new InputStreamReader(sourceUrl.openStream()));
Source source=new Source(htmlText);
source.setLogWriter(new OutputStreamWriter(System.err)); // send log messages to stderr
FormFields formFields=source.findFormFields();
formFields.clearValues(); // clear any values that might be set in the source document
formFields.addValue("Name","Humphrey Bear");
formFields.addValue("Title","Prime Minister");
formFields.addValue("Member","on");
formFields.addValue("Address","The Lodge\nDeakin ACT 2600\nAustralia");
formFields.addValue("MailingList","A");
formFields.addValue("MailingList","B");
formFields.addValue("FavouriteFair","honey");
formFields.addValue("FavouriteSports","BB");
formFields.addValue("FavouriteSports","AFL");
OutputDocument outputDocument=new OutputDocument(source);
outputDocument.add(formFields); // adds all segments necessary to effect changes
// modify stylesheet link since we are now in a different directory
int cssPathPos=htmlText.indexOf("main.css");
outputDocument.add(new StringOutputSegment(cssPathPos,cssPathPos,"data/"));
Writer out=new FileWriter("NewForm.html");
outputDocument.output(out);
out.close();
System.err.println("\nThe form containing new default values has been output to NewForm.html");
System.err.println("This will open automatically in a web browser after you press a key.");
}
}