在 Java 中解析 XML 时 出现的问题,如何使用? (火急!多谢!)

wizz 2001-04-20 06:38:00
使用 sun 的 jaxp-1.1

主要代码:
public class test extends DefaultHandler {

public void startElement(String namespaceURI, String localName,
String qName, Attributes atts)
{ ………… }
public static void main(String[] args)
throws Exception
{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
saxParser.parse(connection.getInputStream(),new test());
}
}

关键问题是在 startElement 里:
1。为何得到的namespaceURI是空,
2。localName 与 qName 有何区别?
3。atts如何使用?

麻烦哪位大侠指点一二,或者有详细资料的连接,小弟感激不尽。。。!!
...全文
213 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
wizz 2001-04-23
  • 打赏
  • 举报
回复
哈哈,我知道了,原来我需要的是 characters 事件,,,,多谢各位,现在给分!
wizz 2001-04-23
  • 打赏
  • 举报
回复
呵呵,谢谢诸位,我现在就试验。。。。

skyyoung, 你那个是IBM的parser吧?我用sun的会不会不同呢?

Zephyr_Boy,没看懂你的话。。。。
Zephyr_Boy 2001-04-22
  • 打赏
  • 举报
回复
这好象除了知道xml中的标志之外,就是io操作了,欢迎有其他意见
skyyoung 2001-04-21
  • 打赏
  • 举报
回复
saxOne.java

这是我们的第一个 SAX 应用。它解析一个 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.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("<?xml version=\"1.0\"?>");
}

/** 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]);
}
}
skyyoung 2001-04-21
  • 打赏
  • 举报
回复
public void startElement(java.lang.String namespaceURI,
java.lang.String localName,
java.lang.String qName,
Attributes atts)
throws SAXException
Receive notification of the beginning of an element.
The Parser will invoke this method at the beginning of every element in the XML document; there will be a corresponding endElement event for every startElement event (even when the element is empty). All of the element's content will be reported, in order, before the corresponding endElement event.

This event allows up to three name components for each element:

the Namespace URI;
the local name; and
the qualified (prefixed) name.
Any or all of these may be provided, depending on the values of the http://xml.org/sax/features/namespaces and the http://xml.org/sax/features/namespace-prefixes properties:

the Namespace URI and local name are required when the namespaces property is true (the default), and are optional when the namespaces property is false (if one is specified, both must be);
the qualified name is required when the namespace-prefixes property is true, and is optional when the namespace-prefixes property is false (the default).
Note that the attribute list provided will contain only attributes with explicit values (specified or defaulted): #IMPLIED attributes will be omitted. The attribute list will contain attributes used for Namespace declarations (xmlns* attributes) only if the http://xml.org/sax/features/namespace-prefixes property is true (it is false by default, and support for a true value is optional).

Parameters:
uri - The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName - The qualified name (with prefix), or the empty string if qualified names are not available.
atts - The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
Dureek 2001-04-21
  • 打赏
  • 举报
回复
是啊, 但是JDOM有SAXBuilder和DOMBuilder, 呵呵 ... 你可根据需要使用, 而且, 可以配合你已有的parser, 比如你用Xerces parser一个xml以后, 可以将Document传给JDOM的builder, 然后剩下的操作由JDOM带劳就好乐, 呵呵 ...

不用客气, 互相学习 :)
wizz 2001-04-20
  • 打赏
  • 举报
回复
Dureek, 你说的JDOM是不是用 DOM 解释?我看资料得到的印象是 DOM 比 SAX 慢,我只需要最简单的提取几个数据。。。那个网站还没有看,星期一再研究吧,,,还是要谢谢你!

诸位高手,不要袖手旁观呀。。。:)
Dureek 2001-04-20
  • 打赏
  • 举报
回复
55555 ... 对不起 ... 不会 :(
我去试试吧 ...
Dureek 2001-04-20
  • 打赏
  • 举报
回复
wizz, 建议你用JDOM试试, 很爽哦~ hehehe ... 而且很可能以后会加入sun的sdk中!

http://www.jdom.org/ 如果下下来getAttribute不行的话, 最好把source codes重新编译一下再打个包就好了 :)

抱歉, 要去吃饭了, 来不及看你的问题了:p 一会儿见, 祝周末愉快 :)
ender 2001-04-20
  • 打赏
  • 举报
回复
关注,我也正要研究这东西……

67,550

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧