Splitting Hairs, Part 3
In this third and final part of a three-part series on splitting up text, we're going to look at using the HTMLDocument class. With some helper classes, you
can work with HTMLDocument to find the elements and attributes within
the document. In part one, we saw how to use the StringTokenizer, and in part two we saw how to use
the StreamTokenizer.
When you use a JEditorPane to display an HTML document, the component stores the content within an HTMLDocument. If you wish to find out what elements are in that HTMLDocument, there are two ways of looking for them. If you are only interested in a specific tag, you can use the HTMLDocument.Iterator class to find each time that specific tag is within the document. If however you wish to work with all the tags, or do different things based upon which tags are present, you would instead need to work with the Element and ElementIterator classes. In this article we'll look at both.
Most of these classes are found in the javax.swing.text.html package. Though some support classes can be found in the javax.swing.text package.
Iterator
The way to use the HTMLDocument.Iterator is to get an iterator for the specific tag you need to find. (All the valid tags are constants in the HTML class.) For instance, to find all the anchor (<A>) tags, you would do the following:
HTMLDocument.Iterator iterator =
htmlDoc.getIterator(HTML.Tag.A);
Once you have the iterator, you walk through the iteration with the next() method, until the iterator's isValid() method reports false, meaning there are no more of those tags around.
while (iterator.isValid()) {
// process element
iterator.next();
}
If you prefer to use a for-loop, you can do the following:
for (HTMLDocument.Iterator iterator =
htmlDoc.getIterator(HTML.Tag.A);
iterator.isValid();
iterator.next()) {
// process element
}
At each stop, you can get the attributes of the element with the getAttributes() method. Then, you would get a specific attribute with the help of one of the constants from the HTML.Attribute class:
AttributeSet attributes = iterator.getAttributes();
String hrefString = (String)
attributes.getAttribute(HTML.Attribute.HREF);
In addition to looking at the attributes, like the HREF attribute of the anchor element, you can look at what text is between the starting and ending tags. To find the starting and ending content, you would use the getStartOffset() and getEndOffset() methods. Once you have the position, you can find the text within the original document:
int startOffset = iterator.getStartOffset();
int endOffset = iterator.getEndOffset();
int length = endOffset - startOffset;
String text = htmlDoc.getText(startOffset, length);
ElementIterator
The ElementIterator is available if you need a little more flexibility within your hunt. Instead of looking for only one tag, you can hunt for many at the same time. Then, based upon which one you find, you act accordingly. To start with the ElementIterator, you create one based upon the Document you are working within:
ElementIterator iterator = new ElementIterator(htmlDoc);
This iterator is not just a forward-looking, one pass iterator. While the basic process is to just keep calling next() until you hit null, you can also call first(), previous(), or current to get other elements. The following just shows the normal case of going from start to end:
Element element;
while ((element = iterator.next()) != null) {
// process element
}
Now that you have an Element, what do you do with it? As with the HTMLDocument.Iterator, you get its AttributeSet. However, this time you must get its name/type. Since we're not just getting one specific tag (like all anchors), you need to look at its StyleConstants.NameAttribute to see what you have.
AttributeSet attributes =
element.getAttributes();
Object name =
attributes.getAttribute(StyleConstants.NameAttribute);
Once you have the appropriate tag, or based upon which tag you have, you process accordingly. Unlike the earlier case with the HTMLDocument.Iterator, if you are interersted in the content you have to find the offsets for that, too. When the StyleConstants.NameAttribute is HTML.Tag.CONTENT you have the content and can find its offsets. Keep in mind that it is possible for the content to be within several sub elements, so you would need to combine each of them:
// Build up content text as
// it may be within multiple elements
StringBuffer text = new StringBuffer();
int count = element.getElementCount();
for (int i=0; i<count; i++) {
Element child = element.getElement(i);
AttributeSet childAttributes = child.getAttributes();
if (childAttributes.getAttribute(
StyleConstants.NameAttribute) ==
HTML.Tag.CONTENT) {
int startOffset = child.getStartOffset();
int endOffset = child.getEndOffset();
int length = endOffset - startOffset;
text.append(htmlDoc.getText(startOffset, length));
}
}
System.out.println(name + ": " + text.toString());
There is definitely much more involved when working with the ElementIterator. If you can get by with working with an HTMLDocument.Iterator, you should definitely try.
Examples
Try using these on your own before looking at an Iterator example or an ElementIterator example. The HTMLDocument.Iterator example displays the text and link URL for all the anchors in a document. The ElementIterator displays all the H1, H2, and H3 headings at a URL. In testing this latter one you may need to create your own HTML document as the tags aren't used that much any more.
The manner in which the HTML files are loaded in the example is completely unnecessary for GUI applications. The GUI component will deal with loading the files asynchronously for you.
Other Tidbits
I'll be back next week with more things to do and places to
go. If you have any comments about this week's feature, be sure
to post them to the bulletin
board. If you have any questions or topic suggestions, let me know or submit feedback.
For technical questions, try to post them to the bulletin board
area, instead of emailing me directly. That way, everyone can
benefit from an answer, as well as offer answers. See you next
time.
Previous Features
|
Sponsored Links |
eHelp Corporation
eHelp Corporation, Worldwide leader in Help authoring. Quickly and easily create WinHelp, HTML Help, JavaHelp, WebHelp, and more.
http://www.ehelp.com/ (Listing fee: $0.36)
|
techies.com
techies.com is the leading career resource for technology professionals. Find the hottest tech jobs. Online training. Valuable career tips. And the inside scoop on local companies.
http://www.techies.com/ (Listing fee: $0.34)
|
Juliet - Navigate Java
Juliet == novel visualization tool. Juliet visualizes all types and packages on your classpath. Use it to: - Explore and understand Java libraries - Quickly lookup details while coding
http://infotectonica.com/ (Listing fee: $0.33)
|
TELECOMMUTING COMPUTER RELATED & I.T. JOBS DIGEST
On average, we post 1,000 to 1,200 work from home computer related and I.T. employment opportunities monthly and we normally don't post less than 800 in any given month.
http://www.intlhomeworkers.com/ (Listing fee: $0.31)
|
Netsetter - the free download accelerator
Download and install the Netsetter software and you can double your internet speed and have a chance to win a BMWZ3 Sports Car!
http://www.commission-junction.com/ (Listing fee: $0.31)
|
|
|
|
 |