Stax解析XML的简单实例

前端之家收集整理的这篇文章主要介绍了Stax解析XML的简单实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

关键字解释:

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对象来写入一个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文档的第一行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();}}
 

    }
原文链接:https://www.f2er.com/xml/296860.html

猜你在找的XML相关文章