Imagine an XML document like this:
<?xml version="1.0" encoding="UTF-8" ?>
<books>
<book name="book1"></book>
<book name="book2"></book>
</books>
I want to write the doc to a new file after filtering out some books. I'm using JOOX and have some code like this:
final FastFilter nameFilter = new FastFilter() {
final Set<String> validNames = new HashSet<>();//contains "book1"
@Override public boolean filter(Context context) {
return !validNames.contains($(context).attr("name"));
}
};
final Document doc = $(new StringReader("entire text of xml document...")).document();
final Match m = $(doc).find("book").remove(nameFilter);
I tried something like this m.write(new File(output.xml));
, but that outputs only:
<book name="book1"></book>
In other words it is missing the parent element <books>
and also the initial XML declaration. Any idea how to accomplish this? Looking for a simple/elegant solution preferably using JOOX, not 20 lines of DOM code :)