如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2008年7月18日星期五

Simple JAXP Application

The Java API for XML Processing, or JAXP (pronounced jaks-p), is one of the Java XML programming APIs. It provides the capability of validating and parsing XML documents. The three basic parsing interfaces are:

    * the Document Object Model parsing interface or DOM interface
    * the Simple API for XML parsing interface or SAX interface
    * the Streaming API for XML or StAX interface (added in JDK 6; separate jar available for JDK 5)

--http://en.wikipedia.org/wiki/Java_API_for_XML_Processing

This tutorial is based on http://www.vogella.de/articles/JavaXML/article.html

We have two XML files to read in this example. They are:

config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
<mode>1</mode>
<unit>900</unit>
<current>1</current>
<interactive>1</interactive>
</config>





person.xml



<?xml version="1.0" encoding="UTF-8"?>
<people>
<person>
<firstname>Lars</firstname>
<lastname>Vogel</lastname>
<city>Heidelberg</city>
</person>

<person>
<firstname>Jim</firstname>
<lastname>Knopf</lastname>
<city>Heidelberg</city>
</person>

<person>
<firstname>Lars</firstname>
<lastname>Strangelastname</lastname>
<city>London</city>
</person>

<person>
<firstname>Landerman</firstname>
<lastname>Petrelli</lastname>
<city>Somewhere</city>
</person>

<person>
<firstname>Lars</firstname>
<lastname>Tim</lastname>
<city>SomewhereElse</city>
</person>

</people>


Now, Here below is a simple Java application to read and write and query XML:



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package hellojaxp;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {

public static void main(String args[]) {
Main object = new Main();
object.readXML("config.xml");
object.writeXML("config2.xml");
object.query("person.xml", null);
}

public void readXML(String path) {

try {
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = new FileInputStream(path);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();

if (event.isStartElement()) {
if (event.asStartElement().getName().getLocalPart().equals("mode")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals("unit")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals("current")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals("interactive")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}

private void createNode(XMLEventWriter eventWriter, String name, String value) {
try {
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
XMLEvent tab = eventFactory.createDTD("\t");
// Create Start node
StartElement sElement = eventFactory.createStartElement("", "", name);
eventWriter.add(tab);
eventWriter.add(sElement);
// Create Content
Characters characters = eventFactory.createCharacters(value);
eventWriter.add(characters);
// Create End node
EndElement eElement = eventFactory.createEndElement("", "", name);
eventWriter.add(eElement);
eventWriter.add(end);
} catch (XMLStreamException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void writeXML(String path) {
try {
// Create a XMLOutputFactory
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// Create XMLEventWriter
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(path));
// Create a EventFactory
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
eventWriter.add(startDocument);

// Create config open tag
StartElement configStartElement = eventFactory.createStartElement("", "", "config");
eventWriter.add(configStartElement);
eventWriter.add(end);
// Write the different nodes
createNode(eventWriter, "mode", "1");
createNode(eventWriter, "unit", "901");
createNode(eventWriter, "current", "0");
createNode(eventWriter, "interactive", "0");

eventWriter.add(eventFactory.createEndElement("", "", "config"));
eventWriter.add(end);
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void query(String path, String keyword) {
try {
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(path);

// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();

// Create a XPath object
XPath xpath = xFactory.newXPath();

// Compile the XPath expression
expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);

// Cast the result to a DOM NodeList
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}

// New XPath expression to get the number of people with name lars
expr = xpath.compile("count(//person[firstname='Lars'])");
// Run the query and get the number of nodes
Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
System.out.println("Number of objects " + number);

// Do we have more then 2 people with name lars?
expr = xpath.compile("count(//person[firstname='Lars']) >2");
// Run the query and get the number of nodes
Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
System.out.println(check);
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


You can download this Netbeans project from


http://www.mediafire.com/?mk445c5msi2

没有评论: