梦相随1006

版权归 梦相随1006 所有,未经 https://www.cnblogs.com/xin1006 作者许可,严禁转载

导航

webservice04#对象与xml转换-jaxb#Stax解析xml#新建修改xml

1,Student类

package com.yangw.xml;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement //作为根节点的元素需要设置这个注解
public class Student {

    private int id;
    private String name;
    private int age;
    private Classroom classroom;
    
    
    public Student(int id, String name, int age, Classroom classroom) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.classroom = classroom;
    }   
    ....  get set ...  
}

2, Classroom对象

package com.yangw.xml;

public class Classroom {

    private  int id;
    private String name;    //班级名称
    private int grade;        //年级
    
    public Classroom(int id, String name, int grade) {
        super();
        this.id = id;
        this.name = name;
        this.grade = grade;
    }
    
    public Classroom() {
        super();
    }  
    ... get  set  ...
}

3, 测试类,对象与xml互转

package com.yangw.xml;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.junit.Test;

public class TestJaxb {

    /**
     * 编排:对象转成xml
     */
    @Test
    public void test01() {
        
        try {
            JAXBContext ctx=JAXBContext.newInstance(Student.class);
            Marshaller marshaller=ctx.createMarshaller();
            
            Student stu=new Student(1,"张",20,new Classroom(1,"软件工程01",2008));
            //参数: 对象,输出流
            marshaller.marshal(stu, System.out);
        } catch (JAXBException e) {
            
            e.printStackTrace();
        }
    }

    /**
     * 反编排:xml转成对象
     */
    @Test
    public void test02() {
        
        try {
            JAXBContext ctx=JAXBContext.newInstance(Student.class);
            Unmarshaller um=ctx.createUnmarshaller();
            
            String xml="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><student><age>20</age><classroom><grade>2008</grade><id>1</id><name>软件工程01</name></classroom><id>1</id><name>张</name></student>";
            //参数: 对象,输出流
            Student stu=(Student)um.unmarshal(new StringReader(xml));
            System.out.println(stu.getName()+"-->"+stu.getClassroom().getName());
        } catch (JAXBException e) {
            
            e.printStackTrace();
        }
    }

}

 4, Stax解析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>

 

package com.yangw.stax;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.EventFilter;
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.Attribute;
import javax.xml.stream.events.XMLEvent;
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 {

    /**
     * Stax,基于光标的解析xml
     */
    @Test
    public void test() {
        //1,创建工厂
        XMLInputFactory factory=XMLInputFactory.newInstance();
        //2,创建XMLStreamReader
        InputStream is=null;
        is=TestStax.class.getClassLoader().getResourceAsStream("books.xml");
        try {
            XMLStreamReader reader=factory.createXMLStreamReader(is);
            
            while(reader.hasNext()){
                switch(reader.next()){
                    case XMLStreamConstants.START_ELEMENT:
                        //获取开始标签名
                        String name=reader.getName().toString();
                        if("book".equals(name)){
                            //获取属性名属性值
                            System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
                        }else if("price".equals(name)){
                            //获取节点的文本
                            System.out.println(reader.getElementText());
                        }
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        break;
                    case XMLStreamConstants.ATTRIBUTE:
                        
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        
                        break;
                    
                        
                }//switch
                
            }//while
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }finally{
            try {
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Stax,基于迭代模型的解析xml
     */
    @SuppressWarnings("unchecked")
    @Test
    public void test02() {
        //1,创建工厂
        XMLInputFactory factory=XMLInputFactory.newInstance();
        //2,创建XMLStreamReader
        InputStream is=null;
        is=TestStax.class.getClassLoader().getResourceAsStream("books.xml");
        try {
            XMLEventReader reader=factory.createXMLEventReader(is);
            
            while(reader.hasNext()){
                //通过XMLEvent来判断是否是某种节点
                XMLEvent event=reader.nextEvent();
                if(event.isStartElement()){
                    //先转换为开始节点,再获取值
                    QName qName=event.asStartElement().getName();
                    
                    if("book".equals(qName.toString())){
                        //获取属性
                        //一个值的方式
                        Attribute attr1= event.asStartElement().getAttributeByName(new QName("category"));
                        System.out.println(attr1.getValue());
                        //多个值进行迭代
                        Iterator<Attribute> it=event.asStartElement().getAttributes();
                        while(it.hasNext()){
                            Attribute attr=it.next();
                            System.out.println(attr.getName()+":"+attr.getValue());
                        }
                    }else if("price".equals(qName.toString())){
                        //获取节点的文本
                        System.out.println(reader.getElementText());
                    }
                }
                
            }//while
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }finally{
            try {
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * Stax,基于迭代模型的解析xml,增加了Filter
     */
    @SuppressWarnings("unchecked")
    @Test
    public void test03() {
        //1,创建工厂
        XMLInputFactory factory=XMLInputFactory.newInstance();
        //2,创建XMLStreamReader
        InputStream is=null;
        is=TestStax.class.getClassLoader().getResourceAsStream("books.xml");
        try {
            //基于Filter的过滤方式,可以有效的过滤掉不用进行操作的节点,效率会高一点
            XMLEventReader reader=factory.createFilteredReader(factory.createXMLEventReader(is), 
                    new EventFilter(){

                @Override
                public boolean accept(XMLEvent event) {
                    //能够接受的条件就返回true
                    if(event.isStartElement()){
                        //假如只过滤book节点
                        String name=event.asStartElement().getName().toString();
                        if("book".equals(name)){
                            return true;
                        }
                    }
                    return false;
                }});
            
            while(reader.hasNext()){
                //通过XMLEvent来判断是否是某种节点
                XMLEvent event=reader.nextEvent();
                if(event.isStartElement()){
                    //先转换为开始节点,再获取值
                    String name=event.asStartElement().getName().toString();
                    
                    if("book".equals(name)){
                        //获取属性
                        //一个值的方式
                        Attribute attr1= event.asStartElement().getAttributeByName(new QName("category"));
                        System.out.println(attr1.getValue());
                        //多个值进行迭代
                        Iterator<Attribute> it=event.asStartElement().getAttributes();
                        while(it.hasNext()){
                            Attribute attr=it.next();
                            System.out.println(attr.getName()+":"+attr.getValue());
                        }
                    }else if("price".equals(name)){
                        //获取节点的文本
                        System.out.println(reader.getElementText());
                    }
                }
                
            }//while
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }finally{
            try {
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * Stax,基于xPath的解析xml,它需要将这个文档加到内存中
     */
    @SuppressWarnings("unchecked")
    @Test
    public void test04() {
        
        InputStream is=null;
        is=TestStax.class.getClassLoader().getResourceAsStream("books.xml");
    
        try {
            //DocumentBuilder
            DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //文档处理对象
            Document doc=builder.parse(is);
            
            XPath xPath=XPathFactory.newInstance().newXPath();
            //使用xPath查找
            // (表达式,源,返回类型急查找出来的类型)
            NodeList list=(NodeList) xPath.evaluate("//book[@category='WEB']", doc, XPathConstants.NODESET);
            for(int i=0;i<list.getLength();i++){
                //Node有很多的子类 ,这个返回的是Element
                Element ele=(Element) list.item(i); //book节点
                //获取该节点的title信息
                System.out.println(ele.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();
        }
            
    
        
    }
}

 5, 写xml。使用Stax

    /**
     * Stax,新建xml
     */
    @SuppressWarnings("unchecked")
    @Test
    public void test05() {
        
        OutputStream ops=null;
        try {
            ops=System.out;
            
            XMLOutputFactory factory=XMLOutputFactory.newInstance();
            XMLStreamWriter writer=factory.createXMLStreamWriter(ops);
            
            writer.writeStartDocument("utf-8", "1.0");
            writer.writeEndDocument();
            
            String ns="http://yangw.com";
            writer.writeStartElement("yang", "person", ns);
            writer.writeNamespace("yang", ns);
            writer.writeNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
            writer.writeAttribute("id","1");
            writer.writeCharacters("yigeren");
            writer.writeEndElement();
            writer.flush();
            writer.close();
        } catch (FactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        
    }
}

6, 修改xml内容

    /**
     * Stax,修改xml节点值,通过 Transformer
   * 先通过Xpath查找,再通过 Transformer修改
*/ @SuppressWarnings("unchecked") @Test public void test06() { InputStream is=null; is=TestStax.class.getClassLoader().getResourceAsStream("books.xml"); try { //DocumentBuilder DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); //文档处理对象 Document doc=builder.parse(is); XPath xPath=XPathFactory.newInstance().newXPath(); Transformer tran=TransformerFactory.newInstance().newTransformer(); tran.setOutputProperty(OutputKeys.ENCODING, "utf-8"); tran.setOutputProperty(OutputKeys.INDENT, "yes"); //使用xPath查找 // (表达式,源,返回类型急查找出来的类型) 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("100.00"); Result result=new StreamResult(System.out); //通过transformer修改节点 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(); } }

 

 

posted on 2014-02-25 16:27  梦相随1006  阅读(423)  评论(0编辑  收藏  举报