Skip to main content

Enabling XML documents for globalization

A simple approach to organizing your translatable XML resources

Return to article


Listing 5: Recognizing translation tags during parse phase

 
  /**
   * Process an XML parser start element event.
   * 
   * Language translation is triggered by the attribute "translatedKey".  If
   * this attribute is specified, the value of the attribute is the look-up
   * key used to fetch the translated strings from a set of translated XML files.
   */
  public void startElement(String uri, String localName, String rawName, Attributes attributes)
  {
    String attribute = null;
    String value = null;
    
    setCurrentElement(localName);

    for (int ndx=0; ndx < attributes.getLength(); ndx++)
    {
      attribute = attributes.getLocalName(ndx);
      value = attributes.getValue(ndx);

      if (isTranslated(attribute))
      {
        // Add to the translatable strings table for translation
        // processing after parsing is complete
        getTranslatableStringsTable().put(getBundleKey(localName), value);
      }
      else
      {
        // Process standard attribute based on a mapping of attributes
        // to method names.
        processEvent(getAttributesMethodMap(), attribute, value);
      }
    }
    // Process element based on a mapping of elements

    // to method names.
    processEvent(getElementStartMethodMap(), getCurrentElement());
  }

  /**
   * Process the characters event. 
   *
   * The characters event is triggered when the parser hits a string of characters
   * coded as the value of an element.
   */
  public void characters(char ch[], int start, int length)
  {
    String elementData = (new String(ch, start, length)).trim();

    if (elementData.length() > 0)
    {
      processEvent(getElementDataMethodMap(), getCurrentElement(), elementData);
    }
  }
  
  /**
   * Determine if the element is translated.
   */
  private boolean isTranslated(String attribute)
  {
    String TRIGGER = "translatedKey";
    return attribute.equalsIgnoreCase(TRIGGER);
  }

Return to article