WEB开发网      婵犵數濮烽弫鍛婄箾閳ь剚绻涙担鍐叉搐绾剧懓鈹戦悩瀹犲闁汇倗鍋撻妵鍕箛閸洘顎嶉梺绋款儑閸犳劙濡甸崟顖氬唨闁靛ě浣插亾閹烘鈷掗柛鏇ㄥ亜椤忣參鏌″畝瀣暠閾伙絽銆掑鐓庣仭缁楁垿姊绘担绛嬪殭婵﹫绠撻、姘愁樄婵犫偓娴g硶鏀介柣妯款嚋瀹搞儱螖閻樺弶鍟炵紒鍌氱Ч瀹曟粏顦寸痪鎯с偢瀵爼宕煎☉妯侯瀳缂備焦顨嗗畝鎼佸蓟閻旈鏆嬮柣妤€鐗嗗▓妤呮⒑鐠団€虫灀闁哄懐濮撮悾鐤亹閹烘繃鏅濋梺闈涚墕濡瑩顢欒箛鏃傜瘈闁汇垽娼ф禒锕傛煕閵娿儳鍩f鐐村姍楠炴﹢顢欓懖鈺嬬幢闂備浇顫夊畷妯肩矓椤旇¥浜归柟鐑樻尭娴滃綊姊虹紒妯虹仸闁挎洍鏅涜灋闁告洦鍨遍埛鎴︽煙閼测晛浠滃┑鈥炽偢閹鈽夐幒鎾寸彇缂備緡鍠栭鍛搭敇閸忕厧绶炴俊顖滅帛濞呭洭姊绘担鐟邦嚋缂佽鍊垮缁樼節閸ャ劍娅囬梺绋挎湰缁嬫捇宕㈤悽鍛婄厽閹兼番鍨婚埊鏇㈡煥濮樿埖鐓熼煫鍥ュ劤缁嬭崵绱掔紒妯肩畺缂佺粯绻堝畷姗€濡歌缁辨繈姊绘担绛嬪殐闁搞劋鍗冲畷顖炲级閹寸姵娈鹃梺缁樻⒒閳峰牓寮崒鐐寸厱闁抽敮鍋撻柡鍛懅濡叉劕螣鐞涒剝鏂€闂佺粯鍔曞Ο濠囧吹閻斿皝鏀芥い鏃囨閸斻倝鎽堕悙鐑樼厱闁哄洢鍔屾晶顖炴煕濞嗗繒绠婚柡灞界Ч瀹曨偊宕熼鈧▍锝囩磽娴f彃浜炬繝銏f硾椤戝洨绮绘ィ鍐╃厵閻庢稒岣跨粻姗€鏌ㄥ☉妯夹fい銊e劦閹瑩顢旈崟顓濈礄闂備浇顕栭崰鏍礊婵犲倻鏆﹂柟顖炲亰濡茶鈹戦埄鍐ㄧ祷妞ゎ厾鍏樺璇测槈閵忕姈鈺呮煏婢跺牆鍔撮柛鏂款槺缁辨挻鎷呯粙搴撳亾閸濄儳鐭撶憸鐗堝笒閺嬩線鏌熼崜褏甯涢柡鍛倐閺屻劑鎮ら崒娑橆伓 ---闂傚倸鍊搁崐鐑芥倿閿旈敮鍋撶粭娑樺幘濞差亜鐓涢柛娑卞幘椤斿棝姊虹捄銊ユ珢闁瑰嚖鎷�
开发学院WEB开发Jsp Java XML教程(附:源程序A) 阅读

Java XML教程(附:源程序A)

 2008-01-05 09:19:39 来源:WEB开发网 闂傚倸鍊搁崐椋庢濮橆兗缂氱憸宥堢亱闂佸湱铏庨崰鏍不椤栫偞鐓ラ柣鏇炲€圭€氾拷闂傚倸鍊搁崐椋庣矆娓氣偓楠炲鏁撻悩鎻掔€梺姹囧灩閻忔艾鐣烽弻銉︾厵闁规鍠栭。濂告煕鎼达紕校闁靛洤瀚伴獮鎺楀箣濠靛啫浜鹃柣銏⑶圭壕濠氭煙閻愵剚鐏辨俊鎻掔墛缁绘盯宕卞Δ鍐冣剝绻涘畝濠佺敖缂佽鲸鎹囧畷鎺戭潩閹典焦鐎搁梻浣烘嚀閸ゆ牠骞忛敓锟�婵犵數濮烽弫鍛婃叏椤撱垹绠柛鎰靛枛瀹告繃銇勯幘瀵哥畼闁硅娲熷缁樼瑹閳ь剙岣胯鐓ら柕鍫濇偪濞差亜惟闁宠桨鑳堕崝锕€顪冮妶鍡楃瑐闁煎啿鐖奸崺濠囧即閵忥紕鍘梺鎼炲劗閺呮稒绂掕缁辨帗娼忛埡浣锋闂佽桨鐒﹂幑鍥极閹剧粯鏅搁柨鐕傛嫹闂傚倸鍊搁崐椋庢濮橆兗缂氱憸宥堢亱闂佸湱铏庨崰鏍不椤栫偞鐓ラ柣鏇炲€圭€氾拷  闂傚倸鍊搁崐鐑芥嚄閼哥數浠氱紓鍌欒兌缁垶銆冮崨鏉戠厺鐎广儱顦崡鎶芥煏韫囨洖校闁诲寒鍓熷铏圭磼濡搫顫嶅銈嗗姉閸樠囧煡婢跺á鐔兼煥鐎n兘鍋撴繝姘拺鐟滅増甯掓禍浼存煕閹惧鈽夐柍缁樻煥椤繈鎳滅喊妯诲闂備礁鎲$粙鎴︺偑閺夋垟鏋旈柡鍐e亾缂佺粯绋撴禒锕傚磼濮橆剦鐎抽梻浣哥-缁垶骞戦崶顒傚祦閻庯綆浜栭弨浠嬫煙闁箑澧い鏂垮€规穱濠囨倷椤忓嫧鍋撻弽褜娼栧┑鐘宠壘閸屻劎鎲歌箛娑樼疅闁圭虎鍠楅弲鎼佹煥閻曞倹瀚�
核心提示:来源:http://d23xapp2.cn.ibm.com/developerWorks/edUCation/xml/xmljava/tutorial/xmljava-1-1.Htmlsonnet.xml 这是在本教程中贯穿使用的示例 XML 文档,Shakespeare William British 1564 16

  来源:http://d23xapp2.cn.ibm.com/developerWorks/edUCation/xml/xmljava/tutorial/xmljava-1-1.Html


sonnet.xml

这是在本教程中贯穿使用的示例 XML 文档。





Shakespeare
William
British
1564
1616



My mistress` eyes are nothing like the sun,
Coral is far more red than her lips red.
If snow be white, why then her breasts are dun,
If hairs be wires, black wires grow on her head.
I have seen roses damasked, red and white,
But no such roses see I in her cheeks.
And in some perfumes is there more delight
Than in the breath that from my mistress reeks.
I love to hear her speak, yet well I know
That music hath a far more pleasing sound.
I grant I never saw a goddess go,
My mistress when she walks, treads on the ground.
And yet, by Heaven, I think my love as rare
As any she belied with false compare.



sonnet.dtd

这是我们示例文档所用的 DTD。




type (Shakespearean Petrarchan) "Shakespearean">

line,line,line,line,
line,line,line,line,
line,line) >

year-of-birth?,year-of-death?) >

domOne.java

这是我们的第一个 DOM 应用。它解析一个 XML 文档并将其内容输出到标准输出。


/*
* (C) Copyright IBM Corp. 1999 All rights reserved.
*
* US Government Users Restricted Rights Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
* The PRogram is provided "as is" without any warranty eXPress or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ibm.xml.parsers.*;

/**
* domOne.java
* Illustrates how to go through a DOM tree.
*/

public class domOne
{
public void parseAndPrint(String uri)
{
Document doc = null;

try
{
DOMParser parser = new DOMParser();
parser.parse(uri);
doc = parser.getDocument();
}
catch (Exception e)
{
System.err.println("Sorry, an error occurred: " + e);
}

// We`ve parsed the document now, so let`s print it.
if (doc != null)
printDOMTree(doc);
}

/** Prints the specified node, then prints all of its children. */
public void printDOMTree(Node node)
{
int type = node.getNodeType();
switch (type)
{
// print the document element
case Node.DOCUMENT_NODE:
{
System.out.println("");
printDOMTree(((Document)node).getDocumentElement());
break;
}

// print element with attributes
case Node.ELEMENT_NODE:
{
System.out.print("<");
System.out.print(node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node attr = attrs.item(i);
System.out.print(" " + attr.getNodeName() +
"="" + attr.getNodeValue() +
""");
}
System.out.println(">");

NodeList children = node.getChildNodes();
if (children != null)
{
int len = children.getLength();
for (int i = 0; i < len; i++)
printDOMTree(children.item(i));
}

break;
}

// handle entity reference nodes
case Node.ENTITY_REFERENCE_NODE:
{
System.out.print("&");
System.out.print(node.getNodeName());
System.out.print(";");
break;
}

// print cdata sections
case Node.CDATA_SECTION_NODE:
{
System.out.print(" System.out.print(node.getNodeValue());
System.out.print("]]>");
break;
}

// print text
case Node.TEXT_NODE:
{
System.out.print(node.getNodeValue());
break;
}

// print processing instruction
case Node.PROCESSING_INSTRUCTION_NODE:
{
System.out.print(" System.out.print(node.getNodeName());
String data = node.getNodeValue();
{
System.out.print(" ");
System.out.print(data);
}
System.out.print("?>");
break;
}
}

if (type == Node.ELEMENT_NODE)
{
System.out.println();
System.out.print(" System.out.print(node.getNodeName());
System.out.print(`>`);
}
}

/** Main program entry point. */
public static void main(String argv[])
{
if (argv.length == 0)
{
System.out.println("Usage: java domOne uri");
System.out.println(" where uri is the URI of the XML document you want to print.");
System.out.println(" Sample: java domOne sonnet.xml");
System.exit(1);
}

domOne d1 = new domOne();
d1.parseAndPrint(argv[0]);
}
}

domCounter.java

这段代码解析一个 XML 文档,然后遍历 DOM 树来采集有关该文档的数据。当数据采集后将其输出到标准输出。


/*
* (C) Copyright IBM Corp. 1999 All rights reserved.
*
* US Government Users Restricted Rights Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ibm.xml.parsers.DOMParser;

/**
* domCounter.java
* This code creates a DOM parser, parses a document, then
* prints statistics about the number and type of nodes
* found in the document.
*/

public class domCounter
{
int documentNodes = 0;
int elementNodes = 0;
int entityReferenceNodes = 0;
int cdataSections = 0;
int textNodes = 0;
int processingInstructions = 0;

public void parseAndCount(String uri)
{
Document doc = null;
try
{
DOMParser parser = new DOMParser();
parser.parse(uri);
doc = parser.getDocument();
}
catch (Exception e)
{
System.err.println("Sorry, an error occurred: " + e);
}

// We`ve parsed the document now, so let`s scan the DOM tree and
// print the statistics.
if (doc != null)
{
scanDOMTree(doc);
System.out.println("Document Statistics for " + uri + ":");
System.out.println("====================================");
System.out.println("Document Nodes: " + documentNodes);
System.out.println("Element Nodes: " + elementNodes);
System.out.println("Entity Reference Nodes: " + entityReferenceNodes);
System.out.println("CDATA Sections: " + cdataSections);
System.out.println("Text Nodes: " + textNodes);
System.out.println("Processing Instructions: " + processingInstructions);
System.out.println(" ----------");
int totalNodes = documentNodes + elementNodes + entityReferenceNodes +
cdataSections + textNodes + processingInstructions;
System.out.println("Total: " + totalNodes + " Nodes");
}
}

/** Scans the DOM tree and counts the different types of nodes. */
public void scanDOMTree(Node node)
{
int type = node.getNodeType();
switch (type)
{
case Node.DOCUMENT_NODE:
documentNodes++;
scanDOMTree(((Document)node).getDocumentElement());
break;

case Node.ELEMENT_NODE:
elementNodes++;
NodeList children = node.getChildNodes();
if (children != null)
{
int len = children.getLength();
for (int i = 0; i < len; i++)
scanDOMTree(children.item(i));
}
break;

case Node.ENTITY_REFERENCE_NODE:
entityReferenceNodes++;
break;

case Node.CDATA_SECTION_NODE:
cdataSections++;
break;

case Node.TEXT_NODE:
textNodes++;
break;

case Node.PROCESSING_INSTRUCTION_NODE:
processingInstructions++;
break;
}
}

/** Main program entry point. */
public static void main(String argv[])
{
if (argv.length == 0)
{
System.out.println("Usage: java domCounter uri");
System.out.println(" where uri is the URI of your XML document.");
System.out.println(" Sample: java domCounter sonnet.xml");
System.exit(1);
}

domCounter dc = new domCounter();
dc.parseAndCount(argv[0]);
}
}



saxOne.java
/*
* (C) Copyright IBM Corp. 1999 All rights reserved.
*
* US Government Users Restricted Rights Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.ParserFactory;

import com.ibm.xml.parsers.SAXParser;

/**
* saxOne.java
* This sample program illustrates how to use a SAX parser. It
* parses a document and writes the document? contents back to
* standard output.
*/

public class saxOne
extends HandlerBase
{
public void parseURI(String uri)
{
SAXParser parser = new SAXParser();
parser.setDocumentHandler(this);
parser.setErrorHandler(this);
try
{
parser.parse(uri);
}
catch (Exception e)
{
System.err.println(e);
}
}

/** Processing instruction. */
public void processingInstruction(String target, String data)
{
System.out.print(" System.out.print(target);
if (data != null && data.length() > 0)
{
System.out.print(` `);
System.out.print(data);
}
System.out.print("?>");
}

/** Start document. */
public void startDocument()
{
System.out.println("");
}

/** Start element. */
public void startElement(String name, AttributeList attrs)
{
System.out.print("<");
System.out.print(name);
if (attrs != null)
{
int len = attrs.getLength();
for (int i = 0; i < len; i++)
{
System.out.print(" ");
System.out.print(attrs.getName(i));
System.out.print("="");
System.out.print(attrs.getValue(i));
System.out.print(""");
}
}
System.out.print(">");
}

/** Characters. */
public void characters(char ch[], int start, int length)
{
System.out.print(new String(ch, start, length));
}

/** Ignorable whitespace. */
public void ignorableWhitespace(char ch[], int start, int length)
{
characters(ch, start, length);
}

/** End element. */
public void endElement(String name)
{
System.out.print(" System.out.print(name);
System.out.print(">");
}

/** End document. */
public void endDocument()
{
// No need to do anything.
}

//
// ErrorHandler methods
//

/** Warning. */
public void warning(SAXParseException ex)
{
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}

/** Error. */
public void error(SAXParseException ex)
{
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}

/** Fatal error. */
public void fatalError(SAXParseException ex)
throws SAXException
{
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}

/** Returns a string of the location. */
private String getLocationString(SAXParseException ex)
{
StringBuffer str = new StringBuffer();

String systemId = ex.getSystemId();
if (systemId != null)
{
int index = systemId.lastIndexOf(`/`);
if (index != -1)
systemId = systemId.substring(index + 1);
str.append(systemId);
}
str.append(`:`);
str.append(ex.getLineNumber());
str.append(`:`);
str.append(ex.getColumnNumber());

return str.toString();
}

/** Main program entry point. */
public static void main(String argv[])
{
if (argv.length == 0)
{
System.out.println("Usage: java saxOne uri");
System.out.println(" where uri is the URI of your XML document.");
System.out.println(" Sample: java saxOne sonnet.xml");
System.exit(1);
}

saxOne s1 = new saxOne();
s1.parseURI(argv[0]);
}
}

saxCounter.java

/*
* (C) Copyright IBM Corp. 1999 All rights reserved.
*
* US Government Users Restricted Rights Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.ParserFactory;
import com.ibm.xml.parsers.SAXParser;

/**
* saxCounter.java
* This sample program calculates statistics for an XML document,
* based on the SAX events received. When the parse is complete,
* it prints the statistics to standard output.
*/

public class saxCounter
extends HandlerBase
{
int startDocumentEvents = 0;
int endDocumentEvents = 0;
int startElementEvents = 0;
int endElementEvents = 0;
int processingInstructionEvents = 0;
int characterEvents = 0;
int ignorableWhitespaceEvents = 0;
int warningEvents = 0;
int errorEvents = 0;
int fatalErrorEvents = 0;

public void parseURI(String uri)
{
SAXParser parser = new SAXParser();
parser.setDocumentHandler(this);
parser.setErrorHandler(this);
try
{
parser.parse(uri);
}
catch (Exception e)
{
System.err.println(e);
}

System.out.println("Document Statistics for " + uri + ":");
System.out.println("====================================");
System.out.println("DocumentHandler Events:");
System.out.println(" startDocument " +
startDocumentEvents);
System.out.println(" endDocument " +
endDocumentEvents);
System.out.println(" startElement " +
startElementEvents);
System.out.println(" endElement " +
endElementEvents);
System.out.println(" processingInstruction " +
processingInstructionEvents);
System.out.println(" character " +
characterEvents);
System.out.println(" ignorableWhitespace " +
ignorableWhitespaceEvents);
System.out.println("ErrorHandler Events:");
System.out.println(" warning " +
warningEvents);
System.out.println(" error " +
errorEvents);
System.out.println(" fatalError " +
fatalErrorEvents);
System.out.println(" ----------");
int totalEvents = startDocumentEvents + endDocumentEvents +
startElementEvents + endElementEvents +
processingInstructionEvents +
characterEvents + ignorableWhitespaceEvents +
warningEvents + errorEvents + fatalErrorEvents;
System.out.println("Total: " +
totalEvents + " Events");
}

/** Processing instruction. */
public void processingInstruction(String target, String data)
{
processingInstructionEvents++;
}

/** Start document. */
public void startDocument()
{
startDocumentEvents++;
}

/** Start element. */
public void startElement(String name, AttributeList attrs)
{
startElementEvents++;
}

/** Characters. */
public void characters(char ch[], int start, int length)
{
characterEvents++;
}

/** Ignorable whitespace. */
public void ignorableWhitespace(char ch[], int start, int length)
{
ignorableWhitespaceEvents++;
}

/** End element. */
public void endElement(String name)
{
endElementEvents++;
}

/** End document. */
public void endDocument()
{
endDocumentEvents++;
}

//
// ErrorHandler methods
//

/** Warning. */
public void warning(SAXParseException ex)
{
warningEvents++;
}

/** Error. */
public void error(SAXParseException ex)
{
errorEvents++;
}

/** Fatal error. */
public void fatalError(SAXParseException ex)
throws SAXException
{
fatalErrorEvents++;
throw ex;
}

/** Main program entry point. */
public static void main(String argv[])
{
if (argv.length == 0)
{
System.out.println("Usage: java saxCounter uri");
System.out.println(" where uri is the URI of your XML document.");
System.out.println(" Sample: java saxCounter sonnet.xml");
System.exit(1);
}

saxCounter sc = new saxCounter();
sc.parseURI(argv[0]);
} }

Tags:Java XML 教程

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接