Stax解析XML的简单实例
来源:程序员人生 发布时间:2015-05-29 08:34:20 阅读次数:2831次
关键字解释:
Stax:Streaming API for XML(用于读写XML的流接口)
xml文件代码:
<?xml version="1.0"?>
<service>
<item>
<task>test</task>
<strategy>repeat</strategy>
</item>
<item>
<task>WebpageRespTask</task>
<strategy>single</strategy>
</item>
</service>
Java代码:Junit4 testcase:TestStax
package unit_test;
import java.io.InputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import org.junit.Test;
public class TestStax {
//基于光标的解析方式
@Test
public void cursorBased() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
is = TestStax.class.getClassLoader().getResourceAsStream("service.xml");
XMLStreamReader reader = null;
try {
reader = factory.createXMLStreamReader(is);
while (reader.hasNext())
{
int type = reader.next();
// System.out.println(reader.next());
// if (type==XMLStreamConstants.START_DOCUMENT||type==XMLStreamConstants.END_DOCUMENT) {
// System.out.println(reader..toString());
// }
if(type==
XMLStreamConstants.START_ELEMENT||type==XMLStreamConstants.END_ELEMENT){
System.out.println(reader.getName().toString());
}
else if(type==XMLStreamConstants.CHARACTERS) {
System.out.println(reader.getText().toString().trim());
}
}
}
catch (XMLStreamException e) {
e.printStackTrace();
}
}
//基于迭代的解析方式
@Test
public void iteratorBased()
{
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
is = TestStax.class.getClassLoader().getResourceAsStream("service.xml");
XMLEventReader reader = null;
try {
reader = factory.createXMLEventReader(is);
while (reader.hasNext())
{
XMLEvent event = reader.nextEvent();
if (event.isStartElement()) {
String name = event.asStartElement().getName().toString();
if (name.equals("strategy")) {
System.out.println(reader.getElementText());
}
}
}
}
catch (XMLStreamException e) {
e.printStackTrace();
}
}
//基于Xpath的情势,解析之前必须先加载全部Dom...DOM--->Document Object Model
@Test
public void testXpath()
{
try {
System.out.println("-------------------------------textXpath----------------------------------------");
InputStream is = TestStax.class.getClassLoader().getSystemResourceAsStream("service.xml");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document dom = db.parse(is);
XPath xpath = XPathFactory.newInstance().newXPath();
String xpStr = "//item[@id='task1']";
NodeList list = (NodeList) xpath.evaluate(xpStr, dom, XPathConstants.NODESET);
System.out.println(list.getLength());
for (int index=0;index<list.getLength();index++) {
Element ele = (Element) list.item(index);
//System.out.println(ele.getNodeName()+" :"+ele.getNodeValue());
System.out.println(ele.getElementsByTagName("task").item(0).getTextContent());
}
System.out.println("-----------------------------------------------------------------------");
}
catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}<pre name="code" class="java"> <pre name="code" class="java">
//通过XMLStreamWriter对象来写入1个xml文档
@Testpublic void writeXml(){try {OutputStream os = new FileOutputStream("person.xml");XMLStreamWriter xmlSW = XMLOutputFactory.newInstance().createXMLStreamWriter(os);//XMLStreamWriter xmlSW = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
//写入xml文档的第1行xmlSW.writeStartDocument("GBK", "1.0"); xmlSW.writeEndDocument(); //写入xml节点 xmlSW.writeStartElement("person"); xmlSW.writeStartElement("perName"); xmlSW.writeCharacters("wuwh"); xmlSW.writeEndElement(); xmlSW.writeEndElement(); //在此方法之前,输出的内容都保存在cache中,
//履行此方法会把存在缓存中数据实际输出。 xmlSW.flush(); xmlSW.close(); } catch (XMLStreamException e) {e.printStackTrace();} catch (FactoryConfigurationError e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch
blocke.printStackTrace();}}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠