XML Light

Examples

 

XMLLight based on a concept of XML elements. XMLLight Element represents any element in XML document, including the root element. An element is a pair of identically named start and end tags. (<text> and </text>). XML element has a name and it may have attributes and a content. Here is a sample of an element "text", with content "Text goes here." and attribute "language" with value "English":
    <text language="English">
        Text goes here.
    </text>
A slash (/) in the end of start tag means that this element does not have a content and it is closed: <text language="English"/>.

1. Read XML document (ReadXMLDocument.java)

Simple demonstration how to read XML document using XMLLight library. Output is on System.out (console).

    // need to clear comments in input document!
    String clearDoc = XMLLight.clearComments(doc);

    // reading root element.
    Element elemRoot = XMLLight.getElem(clearDoc);
    // In this example we did not specify the element name
    // but we can read element using it's name:
    // Element elemRoot = XMLLight.getElem(clearDoc, "PERIODIC_TABLE");

    // check that Element exists in XML document
    if (elemRoot.isNull())
    {
      System.out.println("Null Element");
      return;
    }

    // reading element name
    System.out.println("Root Element name = " + elemRoot.getName());

            // reading element 
            // Please note that new Element class created
            // each time you call method getElem()
    Element elemAtom = elemRoot.getElem("ATOM");
    while (!elemAtom.isNull())
    {
              // reading elements 
      Element elemName   = elemAtom.getElem("NAME");
      Element elemWeight = elemAtom.getElem("ATOMIC_WEIGHT");
      Element elemNumber = elemAtom.getElem("ATOMIC_NUMBER");

                                      // reading element content
      System.out.println("Atom name = '" + elemName.getText() +
                                   // reading attribute with default value N/A
                         "'   State = " + elemAtom.getAttr("STATE", "N/A" ) +
                         "   Weight = " + elemWeight.getText() +
                         "   Number = " + elemNumber.getText());

      // reading next element  from current position
      // Current position for Element elemRoot is the end of
      // last extracted element. See documentation on getPosition()
      // metod for more info.
      elemAtom = elemRoot.getElem("ATOM");
    }
As a result the file 'ReadXMLDocument.xml' parsed and requested data of preiodic table printed. This example included in download package.

2. Create XML document (CreateXMLDocument.java)

Simple demonstration how to create XML document using XMLLight library. Result document (see sample below) has 10 Elements <book>, each containing 100 Elements <chapter>.

    // create root element of XML document
    Element elemDocument = new Element("document");
    // create 10 books in the root Element
    for (int j = 1; j <= 10; j++)
    {
      // create book element
      Element elemBook = new Element("book");
      // set attributes
      elemBook.setAttr("title", "Java & XML Programming. Part " + j);
      elemBook.setAttr("author", "J. Smith");

      // create 100 chapters for each book with attribute 'title'
      // and text sample as a content
      for (int i = 1; i <= 100; i++)
      {
        Element elemChapter = new Element("chapter");
        elemChapter.setAttr("title", ("Chapter " + i));
        elemChapter.addText("Here is a text with entities: &'\"<> And more text... \n");

        // add chapter Element to the book Element
        elemBook.addElem(elemChapter);
      }

      // add book Element to the root Element
      elemDocument.addElem(elemBook);
    }
    // create XML document from the root Element
    String xmlDocument = XMLLight.getXMLDocument(elemDocument);
As a result the file 'CreateXMLDocument.xml' with more then 1000 Elements created in working directory. You can see this file in Microsoft Internet Explorer (v.4 or newer) or using any XML editing program. This example included in download package.

3. Parse XML document (ParseXMLDocument.java)

Simple demonstration how to parse XML document using XMLLight library. Output is on System.out (console). Please note that slow speed is because of the output assigned to the console. Try to comment "System.out.println()" to see the real speed!

  // Reqursively parses the Element
  static void parseElement(Element elem)
  {
    System.out.println("-----------------------------------------");
    System.out.println("Parse element: " + elem.getName());

    // Gets all attributes
    Properties attr = elem.getAttributes();
    for (Enumeration e = attr.keys(); e.hasMoreElements() ;)
    {
      String key = (String) e.nextElement();
      String val = attr.getProperty(key);
      System.out.println("    Attribute: " + key + " = " + val);
    }

    // Gets full text of the Element
    // To read mixed content use Element.getText()
    System.out.println("    Text:");
    System.out.println(elem.getChildText());

    // Find all Sub Elements
    Element subElem = elem.getElem();
    if (!subElem.isNull())
    {
      System.out.println("     SubElements of Element: " + elem.getName());
      while (!subElem.isNull())
      {
        parseElement(subElem);
        subElem = elem.getElem();
      }
    }

    System.out.println("Done  element: " + elem.getName());
  }
As a result the file 'ReadXMLDocument.xml' parsed and all Elements, Attributes and Text are printed. This example included in download package.

4. Read large XML document (ReadLargeXMLDoc.java)

This example shows how XMLLight works with large XML Document. Processed XML dociument is "The Old Testament". The size of the document is about 3.5 MB and it has more then 50,000 tags. The program extracts document title and each book from the document and prints short and long name of the book. For each book program extracts all chapters and prints the title of each chapter. With JDK 1.2 and computer Pentium III 450 MHz all takes less then 1 sec.

    // get the root element
    Element elem = XMLLight.getElem(doc);
    if (elem.isNull())
    {
      System.out.println("null document");
      out.println("null document");
      out.close();
      return;
    }

    out.println("Document title = '" + elem.getElem("coverpg").getElem("title").getText() + "'");

    // get element <book>
    Element elemBook = elem.getElem("book");
    while (!elemBook.isNull())
    {
      out.println("Book. Short name = '" + elemBook.getElem("bktlong").getText() +
                      "' Long name = '" + elemBook.getElem("bktshort").getText() + "'");

      // get element <chapter>
      Element elemChapter = elemBook.getElem("chapter");
      while (!elemChapter.isNull())
      {
        out.println("chapter = '" + elemChapter.getElem("chtitle").getText() + "'");
        elemChapter = elemBook.getElem("chapter");
      }

      elemBook = elem.getElem("book");
    }
As a result the file 'ReadLargeXMLDoc.txt' created containing all output information. This example is not included in download package but you can download it here. Please note that size of compressed file is about 1 MB.

back to XMLLight page

More free downloads

Keywords: SoftCorporation LLC., examples, sample, Java, XML, XSL, XML processing, API, Applet, Java language, tag, element, attribute, software, free, download, application, distributed applications, publishing