[jdom-interest] Simplifications in Element

Mattias J mattias at expertsystem.se
Fri May 23 03:17:09 PDT 2003


Hi there.
In our project I have made a sublass of org.jdom.Element to add some methods
that make the use of JDOM even simpler. Maybe others find the useful too,
and somebody would like to add them to the Element-class itself instead.

The methods are as follows (assuming implemented in the Element class):

  /**
   * Create child.
   */
  public Element createChild(String name)
  {
    Element child = new Element(name);
    this.addContent(child);
    return child;
  }

  /**
   * Add a new child with a text value
   */
  public void setChildText(String name, String value)
  {
    Element child = this.getChild(name);
    if(child == null)
    {
      child = new Element(name);
      this.addContent(child);
    }
    child.setText(value);
  }

Now, to create this XML:
<root>
  <group>
    <tag1>value1</tag1>
    <tag2>value2</tag2>
  </group>
</root>

All I have to write is:
  Element rootElement = new Element("root");
  Element groupElement = rootElement.createChild("group");
  groupElement.setChildText("tag1", "value1");
  groupElement.setChildText("tag2", "value2");

Cheers.

  Mattias Jiderhamn
  Expert Systems




More information about the jdom-interest mailing list