NanoXML/Lite 2.2 |
|||
Chapter 2. Retrieving Data From An XML DatasourceThis chapter shows how to retrieve XML data from a standard data source. Such source can be a file, an HTTP object or a text string.
2.1. A Very Simple Example 2.1. A Very Simple ExampleThis section describes a very simple XML application. It parses XML data from a stream and dumps it to the standard output. While its use is very limited, it shows how to set up a parser and parse an XML document.
import nanoxml.*;
//1
2.2. Analyzing The DataYou can easily traverse the logical tree generated by the parser. By calling on of the parse* methods, you fill an empty XML element with the parsed contents. Every such object can have a name, attributes, #PCDATA content and child objects. The following XML data:
<FOO attr1="fred" attr2="barney"> is parsed to the following objects:
Element FOO: You can retrieve the name of an element using the method getName, thus: FOO.getName() ==> "FOO" You can enumerate the attribute keys using the method enumerateAttributeNames:
Enumeration enum = FOO.enumerateAttributeNames(); You can retrieve the value of an attribute using getAttribute: FOO.getAttribute("attr1") ==> "fred" The child elements can be enumerated using the method enumerateChildren:
Enumeration enum = FOO.enumerateChildren(); If the element contains parsed character data (#PCDATA) as its only child. You can retrieve that data using getContent: BAR.getContent() ==> "Some data." Note that in NanoXML/Lite, a child cannot have children and #PCDATA content at the same time. 2.3. Generating XMLYou can very easily create a tree of XML elements or modify an existing one. To create a new tree, just create an XMLElement object: XMLElement elt = new XMLElement("ElementName"); You can add an attribute to the element by calling setAttribute. elt.setAttribute("key", "value"); You can add a child element to an element by calling addChild:
XMLElement child = new XMLElement("Child"); If an element has no children, you can add #PCDATA content to it using setContent: child.setContent("Some content"); Note that in NanoXML/Lite, a child cannot have children and #PCDATA content at the same time. When you have created or edited the XML element tree, you can write it out to an output stream or writer using the method toString:
java.io.Writer output = ...; |
|||
|