在 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如何使用?

麻烦哪位大侠指点一二,或者有详细资料的连接,小弟感激不尽。。。!!
...全文
263 10 打赏 收藏 转发到动态 举报
写回复
用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
  • 打赏
  • 举报
回复
关注,我也正要研究这东西……
内容概要:本文围绕“基于超局部模型与自抗扰ESO观测器的无模型预测电流控制改进策略”展开研究,提出一种结合超局部模型(ULM)与扩张状态观测器(ESO)的无模型预测电流控制(MFPCC)改进方法,旨在提升永磁同步电机(PMSM)电流环的动态响应性能与抗干扰能力。该策略利用超局部模型对系统行为进行局部逼近,避免依赖精确数学模型,同引入自抗扰控制的ESO实观测并补偿系统内外部扰动,有效抑制参数摄动、负载变化及模型不确定性带来的影响。研究通过Simulink搭建完整的控制系统仿真模型,对传统MFPCC与所提改进策略进行对比分析,验证了新方法在电流跟踪精度、响应速度和鲁棒性方面的优越性。; 适合人群:具备电机控制、现代控制理论及Simulink仿真基础的电气工程、自动化及相关专业的研究生、科研人员及工程技术人员。; 使用场景及目标:①用于高性能电机驱动系统电流环控制器的设计与优化;②为无模型控制与自抗扰控制的融合应用提供技术参考;③支撑相关课题的仿真验证、论文复现与创新方法研究。; 阅读建议:建议读者结合Simulink仿真模型深入理解控制结构与参数整定过程,重点关注ESO的观测性能与扰动补偿机制,并可通过改变负载条件、参数偏差等工况进行鲁棒性测试,进一步掌握该改进策略的核心优势与适用边界。
内容概要:本文围绕Scratch图形化编程平台,详细阐述了《人体感应灯光系统》这一贴近生活的AI科创作品的设计与教学应用。通过模拟真实智能家居人体感应灯的工作原理,利用Scratch的侦测、逻辑判断、亮度特效调节等功能,实现了人物靠近自动亮灯、延熄灭及环境亮度自适应等仿真功能。文章系统拆解了从场景搭建、核心逻辑设计、分层编程实现到调试优化的完整开发流程,并提供了基础版与进阶版可直接导入的源码,支持零基础快速上手与高阶创新拓展。同构建了“基础—进阶—高阶”三层阶梯式教学体系,适配常规课堂、创客社团与赛事培优等多元教学场景,推动小学AI教育的生活化、实践化与创新化发展。 适合人群:小学高年级至初阶段学生,信息技术教师,创客教育从业者,以及参与青少年科创赛事的师生。 使用场景及目标:①作为小学人工智能通识课程的教学案例,帮助学生理解智能感应与控制逻辑;②用于校内创客社团开展项目式学习;③支撑学生参加AI科创类赛事,完成高质量作品创作与答辩准备;④布置为课后综合实践作业,提升动手能力与科技素养。 阅读建议:建议结合提供的Scratch源码进行实践操作,在复现基础上尝试参数调优与功能扩展,如增加音效提示、多区域感应等,深化对编程逻辑与智能系统设计的理解。

67,536

社区成员

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

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