package org.itat.stax;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.EventFilter;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TestStax {
@Test
public void test01() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext()) {
int type = reader.next();
//鍒ゆ柇鑺傜偣绫诲瀷鏄惁鏄紑濮嬫垨鑰呯粨鏉熸垨鑰呮枃鏈妭鐐�涔嬪悗鏍规嵁鎯呭喌鍙婅繘琛屽鐞�
if(type==XMLStreamConstants.START_ELEMENT) {
System.out.println(reader.getName());
} else if(type==XMLStreamConstants.CHARACTERS) {
System.out.println(reader.getText().trim());
} else if(type==XMLStreamConstants.END_ELEMENT) {
System.out.println("/"+reader.getName());
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test02() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext()) {
int type = reader.next();
if(type==XMLStreamConstants.START_ELEMENT) {
String name = reader.getName().toString();
if(name.equals("book")) {
System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test03() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext()) {
int type = reader.next();
if(type==XMLStreamConstants.START_ELEMENT) {
String name = reader.getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test04() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//鍩轰簬杩唬妯″瀷鐨勬搷浣滄柟寮�
XMLEventReader reader = factory.createXMLEventReader(is);
int num = 0;
while(reader.hasNext()) {
//閫氳繃XMLEvent鏉ヨ幏鍙栨槸鍚︽槸鏌愮鑺傜偣绫诲瀷
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//閫氳繃event.asxxx杞崲鑺傜偣
String name = event.asStartElement().getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
num++;
}
System.out.println(num);
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test05() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//鍩轰簬Filter鐨勮繃婊ゆ柟寮忥紝鍙互鏈夋晥鐨勮繃婊ゆ帀涓嶇敤杩涜鎿嶄綔鐨勮妭鐐癸紝鏁堢巼浼氶珮涓�簺
XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is),
new EventFilter() {
@Override
public boolean accept(XMLEvent event) {
//杩斿洖true琛ㄧず浼氭樉绀猴紝杩斿洖false琛ㄧず涓嶆樉绀�
if(event.isStartElement()) {
String name = event.asStartElement().getName().toString();
if(name.equals("title")||name.equals("price"))
return true;
}
return false;
}
});
int num = 0;
while(reader.hasNext()) {
//閫氳繃XMLEvent鏉ヨ幏鍙栨槸鍚︽槸鏌愮鑺傜偣绫诲瀷
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//閫氳繃event.asxxx杞崲鑺傜偣
String name = event.asStartElement().getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
num++;
}
System.out.println(num);
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test06() {
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//鍒涘缓鏂囨。澶勭悊瀵硅薄
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//閫氳繃DocumentBuilder鍒涘缓doc鐨勬枃妗e璞�
Document doc = db.parse(is);
//鍒涘缓XPath
XPath xpath = XPathFactory.newInstance().newXPath();
//绗竴涓弬鏁板氨鏄痻path,绗簩鍙傛暟灏辨槸鏂囨。
NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
for(int i=0;i<list.getLength();i++) {
//閬嶅巻杈撳嚭鐩稿簲鐨勭粨鏋�
Element e = (Element)list.item(i);
System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test07() {
try {
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xsw.writeStartDocument("UTF-8","1.0");
xsw.writeEndDocument();
String ns = "http://11:dd";
xsw.writeStartElement("nsadfsadf","person",ns);
xsw.writeStartElement(ns,"id");
xsw.writeCharacters("1");
xsw.writeEndElement();
xsw.writeEndElement();
xsw.flush();
xsw.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}
@Test
public void test08() {
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//鍒涘缓鏂囨。澶勭悊瀵硅薄
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//閫氳繃DocumentBuilder鍒涘缓doc鐨勬枃妗e璞�
Document doc = db.parse(is);
//鍒涘缓XPath
XPath xpath = XPathFactory.newInstance().newXPath();
Transformer tran = TransformerFactory.newInstance().newTransformer();
tran.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
tran.setOutputProperty(OutputKeys.INDENT, "yes");
//绗竴涓弬鏁板氨鏄痻path,绗簩鍙傛暟灏辨槸鏂囨。
NodeList list = (NodeList)xpath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
//鑾峰彇price鑺傜偣
Element be = (Element)list.item(0);
Element e = (Element)(be.getElementsByTagName("price").item(0));
e.setTextContent("333.9");
Result result = new StreamResult(System.out);
//閫氳繃tranformer淇敼鑺傜偣
tran.transform(new DOMSource(doc), result);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
book.xml
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
分享到:
相关推荐
总的来说,解决"javax.xml.rpc"找不到的问题通常需要检查项目配置,特别是类路径和构建设置,确保所有的依赖都被正确地引入和解析。同时,理解XML-RPC和Web服务的基本概念以及它们在Java环境中的实现,有助于排查和...
其次,`javax.xml.parsers`子包包含了XML解析器的工厂类,如`DocumentBuilderFactory`和`SAXParserFactory`。这些工厂类允许开发者按照需求配置解析器,如是否启用命名空间支持,然后通过`newDocumentBuilder()`或`...
【javax.xml.ws.Service】是Java平台上用于Web服务客户端的一个核心接口,它位于Java Web Services (JWS) API中,主要用于创建和使用Web服务。这个接口是JAX-WS(Java API for XML Web Services)规范的一部分,它...
4. **Java Web Services**:使用javax.xml.soap库,开发者可以轻松地创建和消费Java Web服务。这些服务可以基于SOAP,通过WSDL(Web Services Description Language)进行描述,使用UDDI(Universal Description, ...
1. 添加依赖:将javax.activation.jar库引入你的项目中,通常可以通过设置IDE的构建路径或在pom.xml文件中添加依赖来完成。 2. 创建DataHandler:根据数据源创建DataHandler实例,例如从文件或字节数组创建。 3. ...
1. **javax.xml.ws-api.jar**:这是JAX-WS规范的API接口定义,包含了所有JAX-WS相关的类和接口,如`WebServiceClient`, `WebServiceRef`, `@WebService`等注解。 2. **com.sun.xml.ws.api.jar**:这是JAX-WS RI...
总结起来,`javax.annotation.zip`这个压缩包中的`javax.annotation-api-1.3.2.jar`是Java开发中处理注解的关键库,特别是对于依赖注入和IoC场景,如使用`@Resource`注解进行Bean装配。如果在项目中遇到`@Resource`...
1. 加载XML文档:使用`javax.xml.parsers.DocumentBuilderFactory`类创建一个实例,并调用其`newDocumentBuilder()`方法生成`DocumentBuilder`对象。 2. 解析XML:使用`DocumentBuilder`对象的`parse()`方法读取XML...
在使用javax.ws.rs.jar时,你需要一个支持JAX-RS的容器,如Tomcat或Jetty,这些容器可以解析注解并执行相应的HTTP操作。此外,JAX-RS规范定义了一些可选的实现,比如Apache CXF和Jersey,它们提供了更丰富的功能和...
1. **解析XML**:Java中使用DOM(文档对象模型)、SAX(简单API for XML)或StAX(流式API for XML)等解析器读取XML文件并将其转化为内存中的对象结构。DOM一次性加载整个XML文档,适合小文件;SAX事件驱动,逐行...
为了方便地处理JSON数据,Java提供了`javax.json`包,这是一个标准API,允许开发者对JSON数据进行解析、生成、修改等操作。本文将详细介绍`javax.json`包的主要功能和使用方法。 一、`javax.json`概述 `javax.json`...
6. **Namespace和QName**: 在处理包含命名空间的XML时,JAXB使用`javax.xml.namespace.QName`来表示带有命名空间的元素和属性。`QName`包含了本地名称和命名空间URI。 7. **自定义转换**: 当标准注解无法满足需求时...
Java中使用`org.xml.sax.XMLReader`和`ContentHandler`接口来实现SAX解析。 3. StAX(Streaming API for XML) StAX是基于流的解析器,它允许程序以迭代的方式按需读取XML文档。与SAX相比,StAX提供了更灵活的控制...
1. **配置错误**:你可能在应用的部署描述符(如ejb-jar.xml、web.xml或standalone.xml)中错误地指定了JNDI名称,或者没有正确地将资源绑定到JNDI上下文。 2. **资源未创建**:确保在应用服务器的管理控制台或配置...
使用`javax.wsdl`库,开发者可以进行以下操作: - **解析WSDL文档**:通过`WSDLFactory`创建`Definition`对象,读取并解析WSDL文件。 - **构建WSDL文档**:创建`Definition`对象,添加PortTypes、Bindings和服务,...
at javax.xml.stream.FactoryFinder.newInstance(Unknown Source) at javax.xml.stream.FactoryFinder.newInstance(Unknown Source) at javax.xml.stream.FactoryFinder.find(Unknown Source) at javax.xml....
- **XML**: 处理XML文档,包括解析、生成和转换。 - **JSTL Internationalization (i18n)**: 支持多语言环境。 **2. JSTL与EL(Expression Language)** JSTL与EL一起使用,可以极大地提高JSP页面的效率。EL用于...
javax.xml.bind.annotation.adapters XmlAdapter 及其规范定义的子类允许任意 Java 类与 JAXB 一起使用。 javax.xml.bind.attachment 此包由基于 MIME 的包处理器实现,该处理器能够解释并创建基于 MIME 的包格式的...
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "person") public class Person { private String name; private int age; @XmlElement public String getName() { return name; ...
8. XSLT: 是一种转换XML文档的语言,使用`javax.xml.transform.TransformerFactory`和`javax.xml.transform.Source`可以实现XSLT转换。 通过这些API,开发者可以根据需求选择最适合的XML处理方式,不论是小型还是...