★ wanayoo — archive 1999 http://java.about.com/compute/java/library/weekly/aa010800a.htmNouvelle recherche | Portail wanayoo
Enter Sweepstakes! · Advertise on this site · Get Bargains
About.com  
You are here:  About > Computing/Technology > Focus on Java
an About site
   About.com
 
 One of Over 700 Sites
Your Guide with Guide
John Zukowski
Bio | Contact

Subjects
Applets
Book Resources
Career Resources
Community
Core Libraries
FAQs
Getting Started
How-To
Magazines
News Sources
Tools
Tutorials

Subject Library 

All articles on this topic

Bookstore
Find books related to this topic Click Here

Videostore
Find videos related to this topic Click Here

ShoppingAbout
Your favorite products, right here Click Here

Stay up-to-date!
Subscribe to our newsletter.

Do you like our sites?
Wish to share them with others - and earn money?
Become an Affiliate

More Sites on this Topic
Java Coffee Break

Search for 
in   Sites A to Z
 
 

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

Subscribe to The Focus on Java Newsletter
Name
Email



Email this page!

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)
Sponsor this site More...


 
 Advertising
AllBusiness.com
Create your business plan. Here’s how.

Casino Online
Act NOW for 20% Cash Bonus $$

HotJobs.com
Better Jobs for a Better Life

Wanna be famous?
Win a walk-on part in a new movie.

single pixel
single pixel
Marketplace
register domains
get a website$499
long distance deal
- - free stuff - -
meet your match
virtual makeover
high paying jobs
quick jobs search
free ebiz solutions
meet your match
build a business
$50 off mp3 player
meet your match
book club
longdistancedeal

 
Related sites
single pixel
on About 
C/C++
Computer Science
Focus on JavaScript
Focus on Web3D
HTML
Internet Industry
Perl
Web Design
XML


Explore More On The About Network
Search
Arts/Humanities ·  Autos ·  Cities/Towns ·  Comedy ·  Computing/Technology ·  Cultures ·  Education ·  Food/Drink ·  Gadgets ·  Games ·  Health/Fitness ·  Hobbies ·  Home/Garden ·  Homework Help ·  Industry ·  Internet/Online ·  Jobs/Careers ·  Kids ·  Money ·  Movies ·  Music/Performing Arts  ·  News/Issues ·  Parenting/Family ·  People/Relationships ·  Pets ·  Recreation/Outdoors ·  Real Estate ·  Religion/Spirtuality ·  Science ·  Shopping ·  Small Business ·  Sports ·  Style ·  Teens ·  Travel ·  TV/Radio · 
 
single pixel

For more information, visit
Our Story, Be a Guide, or Advertise. For rules of use,
read our User Agreement and
Privacy & Kids Privacy Policy.

Having a problem?
Report it here.

About Canada   ·    About UK

 
Copyright  © 2000 About.com, Inc.
About and About.com are registered trademarks of About.com, Inc.
The About logo is a trademark of About.com, Inc.
All rights reserved.