Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Tuesday, May 19, 2009

org.w3c.dom.Document

更多精彩请到 http://www.139ya.com

From : http://kickjava.com/2515.htm



import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;


File f; // The file to parse. Assume this is initialized elsewhere


// Create a factory object for creating DOM parsers
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
// Now use the factory to create a DOM parser ( a.k.a. a DocumentBuilder )
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
// Parse the file and build a Document tree to represent its content
Document document = parser.parse ( f ) ;
// Ask the document for a list of all < sect1 > tags it contains
NodeList sections = document.getElementsByTagName ( "sect1" ) ;
// Loop through those < sect1 > elements one at a time, and extract the
// content of their < h3 > tags.
int numSections = sections.getLength ( ) ;
for ( int i = 0; i < numSections; i++ ) {
Element section = ( Element ) sections.item ( i ) ; // A < sect1 >
// Find the first element child of this section ( a < h3 > element )
// and print the text it contains.
Node title = section.getFirstChild ( ) ;
while ( title != null && title.getNodeType ( ) != Node.ELEMENT_NODE )
title = title.getNextSibling ( ) ;
// Print the text contained in the Text node child of this element
if ( title!=null ) System.out.println ( title.getFirstChild ( ) .getNodeValue ( ) ) ;
}


Creating XML Document using DOM

更多精彩请到 http://www.139ya.com

From : http://www.javareference.com/jrexamples/viewexample.jsp?id=63

Creating XML Document using DOM
[ contributed by Darshan Singh ]
bookmark this on del.icio.us Discuss this Example with Darshan Singh
Print E-Mail
Description:
This example reads a CSV file and creates an XML document from it. The first line in the CSV file is assumed to be the field/column names, and these names are used as element names in the XML document. Like in previous example, DocumentBuilderFactory is used to create an instance of DocumentBuilder class. This time we call newDocument method on DocumentBuilder. This method returns an instance of org.w3c.dom.Document class that is then used to create XML document by calling methods such as createElement and appendChild.


Example Code:
The main function creates an instance of CSV2XML class and calls convertFile method. This method starts reading the CSV file. It uses stringTokenizer to first get the column names (from the first row) and then the actual data items (for each row starting second row in the file) and creates XML elements.
The below code uses JAXP classes TransformerFactory and Transformer to save the document. The alternative approach would be to use org.apache.crimson.tree.XmlDocument class as below:

BufferedWriter bufferWriter = new BufferedWriter(new FileWriter(xmlFileName));

XmlDocument xDoc = (XmlDocument)newDoc;
xDoc.write(bufferWriter);

bufferWriter.close();"



/**
* DOM Example: Creating XML document by converting CSV file to XML
* First line in CSV file is field/column names -
* which is also used as element names while creating XML document
*/
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class CSV2XML {

// Protected Properties
protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;

// CTOR
public CSV2XML()
{
try
{
domFactory = DocumentBuilderFactory.newInstance();
domBuilder = domFactory.newDocumentBuilder();
}
catch(FactoryConfigurationError exp)
{
System.err.println(exp.toString());
}
catch(ParserConfigurationException exp)
{
System.err.println(exp.toString());
}
catch(Exception exp)
{
System.err.println(exp.toString());
}
}

public int convertFile(String csvFileName, String xmlFileName)
{
int rowsCount = -1;
try
{
Document newDoc = domBuilder.newDocument();

// Root element
Element rootElement = newDoc.createElement("CSV2XML");
newDoc.appendChild(rootElement);

// Read comma seperated file
BufferedReader csvReader;
csvReader = new BufferedReader(new FileReader(csvFileName));
int fieldCount = 0;
String[] csvFields = null;
StringTokenizer stringTokenizer = null;

// Assumption: first line in CSV file is column/field names
// As the column names are used to name the elements in the XML file,
// avoid using spaces/any other characters not suitable for XML element naming
String curLine = csvReader.readLine();
if(curLine != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
if(fieldCount > 0)
{
csvFields = new String[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}

// Now we know the columns, now read data row lines
while((curLine = csvReader.readLine()) != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();

if(fieldCount > 0)
{
Element rowElement = newDoc.createElement("row");

int i=0;
while(stringTokenizer.hasMoreElements())
{
try
{
String curValue = String.valueOf(stringTokenizer.nextElement());
Element curElement = newDoc.createElement(csvFields[i++]);
curElement.appendChild(newDoc.createTextNode(curValue));
rowElement.appendChild(curElement);
}
catch(Exception exp)
{
}
}

rootElement.appendChild(rowElement);
rowsCount++;
}

}

csvReader.close();

// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(newDoc);
Result dest = new StreamResult(new File(xmlFileName));
aTransformer.transform(src, dest);

rowsCount++;
}
catch(IOException exp)
{
System.err.println(exp.toString());
}
catch(Exception exp)
{
System.err.println(exp.toString());
}

return rowsCount;
}

public static void main(String[] args)
{
try
{
if(args.length != 2)
{
System.out.println("Usage: java CSV2XML ");
return;
}
}
catch(Exception exp)
{
System.err.println(exp.toString());
}

try
{
CSV2XML csvConverter = new CSV2XML();
int rowsCount = csvConverter.convertFile(args[0], args[1]);

if(rowsCount >= 0)
{
System.out.println("CSV File " + args[0] +
"' successfully converted to XML File "+ args[1] + "\n" +
"(" + String.valueOf(rowsCount) + " rows)");
}
else
{
System.out.println("Error while converting input CSV File " + args[0] +
" to output XML File "+ args[1] + " ");
}
}
catch(Exception exp)
{
System.err.println(exp.toString());
}
}
}

Wednesday, January 14, 2009

JDOM 介绍及使用指南

更多精彩请到 http://www.139ya.com

JDOM 介绍及使用指南: http://blog.csdn.net/duzhiteng/archive/2007/10/07/1814328.aspx

一、JDOM 简介
JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析、生成、序列化以及多种操作。
JDOM 直接为JAVA编程服务。它利用更为强有力的JAVA语言的诸多特性(方法重载、集合概念以及映射),把SAX和DOM的功能有效地结合起来。
在使用设计上尽可能地隐藏原来使用XML过程中的复杂性。利用JDOM处理XML文档将是一件轻松、简单的事。
JDOM 在2000年的春天被Brett McLaughlin和Jason Hunter开发出来,以弥补DOM及SAX在实际应用当中的不足之处。
这些不足之处主要在于SAX没有文档修改、随机访问以及输出的功能,而对于DOM来说,JAVA程序员在使用时来用起来总觉得不太方便。
DOM 的缺点主要是来自于由于Dom是一个接口定义语言(IDL),它的任务是在不同语言实现中的一个最低的通用标准,并不是为JAVA特别设计的。JDOM的最新版本为JDOM Beta 9。最近JDOM被收录到JSR-102内,这标志着JDOM成为了JAVA平台组成的一部分。


二、JDOM 包概览
JDOM是由以下几个包组成的
org.JDOM
org.JDOM.input
org.JDOM.output
org.JDOM.adapters
org.JDOM.transform

Sunday, January 11, 2009

Apache Xerces2(Xerces-J) - Java开源XML处理框架

更多精彩请到 http://www.139ya.com

Apache Xerces2(Xerces-J) - Java开源XML处理框架

Xerces-J发布在较为宽松的Apache开放源代码授权之下,同时由于其出色的稳定性,强大的功能等特征,Xerces-J是现在被用得最广泛的XML处理器之一。

Xerces-J实现了W3C(一个定义各种标准的国际组织)的DOM(Document Object Model)API标准以及SAX(Simple API for XML)规格。

Java操作xml的方法以及xalan, xerces, crimson三者的关系

更多精彩请到 http://www.139ya.com

转自: Java操作xml的方法以及xalan, xerces, crimson三者的关系

Java语言编程中更新XML文档的四种方法。第一种方法是直接读写XML文件。第二种方法是使用Apache Crimson的XmlDocument类,这种方法极为简单,使用方便,如果你选用Apache Crimson作为XML解析器,那么不妨使用这种方法,不过这种方法似乎效率不高(源于效率低下的Apache Crimson),另外,高版本的JAXP或者是Java XML Pack、JWSDP不直接支持Apache Crimson,亦即这种方法不通用。第三种方法是使用JAXP的XSLT引擎(Transformer类)来输出XML文档,这种方法也许是标准的方法了,使用起来十分灵活,特别是可以自如控制输出格式,我们推荐采用这种方法。第四种方法是第三种方法的变种,采用了Xalan XML Serializer,引入了串行化操作,对于大量文档的修改/输出有优越性,可惜的是要重复设置XSLT引擎的属性和XML Serializer的输出属性,比较麻烦,而且依赖于Apache Xalan和Apache Xerces技术,通用性略显不足。除此之外,实际上应用别的API(比如dom4j、JDOM、Castor、XML4J、Oracle XML Parser V2)也有很多办法可以更新XML文档。

概念介绍
Xerces/Crimson是XML解析器,Xalan是XSLT处理器,xml-apis.jar实际上是JAXP。
Apache Crimson的前身是Sun Project X Parser, 至今Apache Crimson的很多代码都是从X Parser中直接移植过来的。早期的JAXP是和X Parser捆绑在一起的。后来的 JAXP和Apache Crimson捆绑在一起,比如JAXP 1.1。最新的JAXP 1.2 EA(Early Access)改弦更张,采用性能更好的Apache Xalan和Apache Xerces分别作为XSLT处理器和XML解析器,不能直接支持Apache Crimson了。
dom4j(dom4j.jar)是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在SourceForge上找到它。在IBM developerWorks上面可以找到一篇文章,对主流的Java XML API进行的性能、功能和易用性的评测,dom4j无论在那个方面都是非常出色的。

DOM与SAX的区别

更多精彩请到 http://www.139ya.com

1.

SAX是parser的一种,它是event driven的,它不会一次把一个XML全parse完,只会解析一点,当遇到某个新的起点或终点时,调一个回调函数。如果程序要找到前面的元素是没有办法的,除非程序自己用某种方式先保存好。

DOM将文档保存成一个树形的数据结构,非常方便,但是明显用的内存更多。

DOM and SAX parsers work in different ways. A SAX parser processes the XML document as it parses the XML input stream, passing SAX events to a programmer-defined handler method. A DOM parser, on the other hand, parses the entire input XML stream and returns a Document object. Document is the programmatic, language-neutral interface that represents a document. The Document returned by the DOM parser has an API that lets you manipulate a (virtual) tree of Node objects; this tree represents the structure of the input XML.*

http://www.javaworld.com/jw-07-2000/jw-0707-xmldom.html?page=1

2.

SAX概念
SAX是Simple API for XML的缩写,它并不是由W3C官方所提出的标准,可以说是“民间”的事实标准。实际上,它是一种社区性质的讨论产物。虽然如此,在XML中对SAX的应用丝毫不比DOM少,几乎所有的XML解析器都会支持它。

与 DOM比较而言,SAX是一种轻量型的方法。我们知道,在处理DOM的时候,我们需要读入整个的XML文档,然后在内存中创建DOM树,生成DOM树上的每个Node对象。当文档比较小的时候,这不会造成什么问题,但是一旦文档大起来,处理DOM就会变得相当费时费力。特别是其对于内存的需求,也将是成倍的增长,以至于在某些应用中使用DOM是一件很不划算的事(比如在applet中)。这时候,一个较好的替代解决方法就是SAX。

SAX 在概念上与DOM完全不同。首先,不同于DOM的文档驱动,它是事件驱动的,也就是说,它并不需要读入整个文档,而文档的读入过程也就是SAX的解析过程。所谓事件驱动,是指一种基于回调(callback)机制的程序运行方法。(如果你对Java新的代理事件模型比较清楚的话,就会很容易理解这种机制了)


在XMLReader接受XML文档,在读入XML文档的过程中就进行解析,也就是说读入文档的过程和解析的过程是同时进行的,这和DOM区别很大。解析开始之前,需要向XMLReader注册一个ContentHandler,也就是相当于一个事件监听器,在 ContentHandler中定义了很多方法,比如startDocument(),它定制了当在解析过程中,遇到文档开始时应该处理的事情。当 XMLReader读到合适的内容,就会抛出相应的事件,并把这个事件的处理权代理给ContentHandler,调用其相应的方法进行响应。



What is the difference between a DOMParser and a SAXParser?

DOM parsers and SAX parsers work in different ways.

* A DOM parser creates a tree structure in memory from the input document and then waits for requests from client. But a SAX parser does not create any internal structure. Instead, it takes the occurrences of components of a input document as events, and tells the client what it reads as it reads through the input document.
* A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. But a SAX parser serves the client application always only with pieces of the document at any given time.
* With DOM parser, method calls in client application have to be explicit and forms a kind of chain. But with SAX, some certain methods (usually overriden by the cient) will be invoked automatically (implicitly) in a way which is called "callback" when some certain events occur. These methods do not have to be called explicitly by the client, though we could call them explicitly.

DOM和SAX比较和选择

更多精彩请到 http://www.139ya.com

转自: DOM和SAX比较和选择
当解析一个XML时我们有很多选择方案,如SAX、DOM、JDOM、JAXP、数据绑定等等,必须根据实际情况来选择一个或几个。在此仅谈论SAX和DOM,可以从以上四点考虑,选择合适的解析器。

1. SAX提供的模型不允许对XML文件随机存取
如:当前解析到第3个Element,此时程序无法得到第5个Element的信息,因为还没有解析到第5个Element;同样也无法得到第1个 Element的信息,因为已经丢失了。当然可以通过声明变量保存解析过的数据,但这如同手动在内存中构造了某种数据结构,一般都是树型结构,这相当麻烦且没有必要,因为DOM恰恰提供了这样一个内存中的模型。

2.SAX模型中元素之间的横向移动困难
SAX提供的是层次型的解析,便利所有第1个Element的子节点(一直到叶子节点)后,才可能开始解析下一个兄弟Element。而且很难知道某一时刻,解析到了哪个层次节点了。DOM则可以很好的解决这个问题,可以方便的找到任何兄弟节点。

3.SAX是熊瞎子劈苞米
SAX是解析一个节点后回调一个方法,把该节点相关信息传送个调用者,然后丢弃这些信息,继续解析下一个节点。正是这样一个机制,使得SAX占用内存很少,它不会预存储整个XML文档,也不会在解析后保存任何解析结果。而DOM则正好相反,把整个XML加载进内存中,即使是延迟加载策略,也会浪费额外的性能为代价。所以当XML非常庞大的时候,还是需要首选SAX。

4.SAX的修改XML能力差
尽管SAX2.0提供了XMLWriter,但是大量的修改XML,还是不建议采用它来完成。XMLWriter更适合记录解析过程的日志。而DOM则具有强大的修改模型的能力,进而保存更新后的XML。

下面分别详细介绍DOM和SAX:

XML的DOM解析器
DOM(Document Object Model)是W3C指定的,它不是专门为Java或其他语言而制定的,所以有些地方不大符合Java的风格,如使用NodeList和NameNodeMap而没有使用Java的集合框架类。
DOM把XML在内存中生成一个树结构,了解其结构也就基本了解了DOM。基本结构的主要接口为:
Node <- Document
<- DocumentType
<- Element
<- Entity
<- CharacterData <- Comment
<- Text <- CDATA
所有接口都是扩展Node的,也就是说树中的任何东西都是Node,所以Node是很重要的接口。通过Node的getNodeType()和getNodeValue()分别可以得到节点的类型和节点的值。

节点类型有:
Node.DOCUMENT_NODE
Node.ELEMENT_NODE
Node.TEXT_NODE
Node.CDATA_SECTION_NODE
Node.PROCESSING_INSTRUCTION_NODE
Node.ENTITY_REFERENCE_NODE
Node.DOCUMENT_TYPE_NODE
可以通过以下方式判断
switch(node.getNodeType()){
case Node.Document_NODE:
//...
case Node.ELEMENT_NODE:
//...
}

开始解析:
URI xmlUri=new URI("xml file address");
DOMParser parser = new DOMParser();
parser.parse(xmlUri);
Document doc = parser.getDocument();
不同的解析器的构造方式不同,有的解析器会直接返回Document对象,如下:
Document doc = parser.parse(xmlUri);
Element rootElement = doc.getDocumentElement();
NodeList childrenNodes=rootElement.getChildNodes();
依次类推就可以遍历所有节点,分别处理每个节点即可。值得注意的是文本也是一个节点Text,但是属性则不是一个节点,可以通过Elemenet.getAttributes()获得。其他的也没什么了,参考一下DOM的JavaDoc就OK了。

------值得注意的细节------
1.性能与内存
DOM解析器会把所有的XML文档全部加载到内存中,如果XML文件非常庞大,那么这样的解析器会耗尽内存,导致内存益处异常;当前,很多解析器已经采用了延迟加载设计模式(类似于Hibernate的lazy策略),即只有当具体用刀某个节点数据的时候再去加载该节点,不用的就不加载,这种策略节省了内存的浪费,但是对性能有一定影响。这是有得必有失,需要根据实际情况而定采用什么策略。

2.Node的属性
因为所有节点都是继承Node的,所以任何节点都可以调用getNodeType(),getNodeValue(),getNodeName()之类的方法,但是并不是这些方法对任何节点都有效,比如说对于Element来说,getNodeValue()就无效,因为Element下的文本是Text 类表示的,而不是一个String。

3.SAXException
当使用DOM解析器时,如果出现了SAXException,不用惊讶。

XML的SAX解析器
SAX解析器是通过回调的方式来执行XML的解析工作的。对于基本的解析操作还是比较简单的,就是实现SAX2.0定义的四个核心接口,并注册进解析器即可。具体的操作都在四个接口中的回调方法中。所谓回调,我理解它与.Net中的事件类似。

XSLT 处理程序是如何工作的

更多精彩请到 http://www.139ya.com


XSLT 处理程序是如何工作的

English Version

XSLT 介绍

更多精彩请到 http://www.139ya.com

转自:http://www.w3pop.com/learn/view/p/1/o/0/doc/xsl_intro/

XSLT 介绍

XSLT is a language for transforming XML documents into XHTML documents or to other XML documents.
XSLT是一种把XML文件转换成XHTML文档或者其他的XML文档的语言。

XPath is a language for navigating in XML documents.
XPath是一种用于导航XML文档的语言。


XSLT stands for XML / XSL Transformations
XSLT是一种用来转换XML / XSL文档结构的语言
XSLT is the most important part of XSL
XSLT是XSL最重要的部分
XSLT transforms an XML document into another XML document
XSLT可以把XML文档转换成另一个XML文档
XSLT uses XPath to navigate in XML documents
XSLT通过XPath对XML文档进行定位
XSLT is a W3C Recommendation
XSLT是一种W3C推荐标准


XSLT = XSL Transformations
XSLT=XSL转换


XSLT is the most important part of XSL.
XSLT是XSL的最重要的一部分。

XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.
XSLT用于把XML文档转换成其它的XML文件,或者转换成另一种能被浏览器所识别的诸如HTML和XHTML类型的文档。通常情况下,XSLT是通过把每个XML元素转换成一个(X)HTML元素来完成的。

With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more.
通过XSLT,你可以在已输出的文件里添加或删除元素和属性。你也可以把元素重新进行排列和分类,执行测试语句,决定是否隐藏元素,或者实现其它更多的功能。

A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-tree.
我们通常这样来描述转换过程:XSLT把XML树形结构源文件换成XML树形结果。

XSLT Uses XPath
XSLT使用XPath的方法

XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and attributes in XML documents.
XSLT使用XPath查找XML文档中的信息。XPath用于对XML文件中的元素和属性进行定位或导航


How Does it Work?
它是怎样运行的?

In the transformation process, XSLT uses XPath to define parts of the source document that should match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document.
在转换过程当中,XSLT使用XPath来定义源文档的某些部分,而这些源文档必须与一个或多个预定义的模版相匹配。当其中一个所匹配的源文件被找到以后,XSLT将会把这个源文件中相匹配的部分转换到结果文档中。