Reputation: 1498
I have coded a Java program using Watcher API which checks for a folder and whenever a file is created, it adds a particular value in html tag.
This is my WATCHER API Java class:
package com.searchtechnologies;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
public class WatcherAPI {
public static void main(String args[]) {
Path myDir = Paths.get("C:/Apps/CollectionOfXMLFiles");
try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
String fileName = "" + event.context();
HtmlParser htmlParser = new HtmlParser();
htmlParser.HTMLtag(fileName);
}
}
}
catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}
}
This is my HTMLParser.java
public void HTMLtag(String fileName) throws IOException {
File file = new File("firstpage.html");
Document doc = Jsoup.parse(file, "UTF-8");
fileName = fileName.substring(0, fileName.length() - 4);
String collection = fileName;
doc.select("select").first().children().first()
.before("<option value=" + collection + ">" + collection + "</option");
PrintWriter writer = new PrintWriter("firstpage.html");
writer.write(doc.toString());
writer.close();
}
It is appending the name of file in this tag:
<td valign="middle"><select name="site">
<option value="collection">collection</option>
Suppose if the name of my file is default_collection.xml, my java program extract the name of the xml file which is default_collection and adds this in my html file:
<td valign="middle"><select name="site">
<option value="default_collection">default_collection</option>
But instead of adding it one time, my java program is adding the collection twice:
<td valign="middle"><select name="site">
<option value="default_collection">default_collection</option>
<option value="default_collection">default_collection</option>
I am not sure what the problem is. Any help would be appreciated.
Upvotes: 1
Views: 757
Reputation: 44965
You should use prepend
instead, it is more appropriate in your case
Add the supplied HTML to the start of each matched element's inner HTML.
The code this then:
doc.select("select")
.prepend("<option value=" + collection + ">" + collection + "</option");
You should also try to be as accurate as you can in your CSS selector to prevent unexpected match. Here for example your selector could be table tr td select
Upvotes: 2