Java操作XML(4)--使用woodstox处理XML

2021-03-05 01:26

阅读:410

标签:sch   class   efi   filter   html   代码   rac   element   tin   

    Woodstox是一个快速、开源的StAX实现;被视为执行效果最佳的StAX实现之一。本文主要介绍使用Woodstox来理XML,文中所使用到的软件版本:Java 1.8.0_191、woodstox-core-asl 4.4.1。

1、引入依赖

dependency>
    groupId>org.codehaus.woodstoxgroupId>
    artifactId>woodstox-core-aslartifactId>
    version>4.4.1version>
dependency>

2、Java代码例子

该例子演示如何使用Woodstox来解析XML以及使用Woodstox来生成XML。

package com.abc.demo.general.xml;

import org.codehaus.stax2.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import javax.xml.stream.*;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;

/**
 * 使用Woodstox处理xml
 */
public class WoodstoxCase {
    private static Logger logger = LoggerFactory.getLogger(WoodstoxCase.class);

    /**
     * 基于光标的方式解析xml
     * @throws Exception
     */
    @Test
    public void parse() throws Exception {
        XMLInputFactory2 factory = (XMLInputFactory2)XMLInputFactory2.newFactory();
        XMLStreamReader2 reader = (XMLStreamReader2)factory.createXMLStreamReader(WoodstoxCase.class.getResourceAsStream("student.xml"));
        //添加过滤器
        XMLStreamReader2 filterReader = (XMLStreamReader2)factory.createFilteredReader(reader, new StreamFilter() {
            @Override
            public boolean accept(XMLStreamReader reader) {
                //处理开始节点
                if (reader.isStartElement()) {
                    return true;
                }
                return false;
            }
        });

        while (filterReader.hasNext()) {
            int type = filterReader.next();
            if (type == XMLStreamReader.START_ELEMENT) {
                if ("student".equals(reader.getName().getLocalPart())) {
                    logger.info("rollno:" + reader.getAttributeValue("", "rollno"));
                } else if ("firstname".equals(reader.getName().getLocalPart())
                        || "lastname".equals(reader.getName().getLocalPart())
                        || "nickname".equals(reader.getName().getLocalPart())
                        || "marks".equals(reader.getName().getLocalPart())) {
                    logger.info(reader.getName().getLocalPart() + ":" + reader.getElementText());
                } else {
                    continue;
                }

            }
//            else if (type == XMLStreamReader.CHARACTERS){
//                logger.info(reader.getText());
//
//            } else if (type == XMLStreamReader.END_ELEMENT) {
//                logger.info("END_ELEMENT:" + reader.getName().getLocalPart() + ">");
//            }
        }
    }

    /**
     * 基于迭代模型的方式解析xml
     * @throws Exception
     */
    @Test
    public void parse2() throws Exception {
        XMLInputFactory2 factory = (XMLInputFactory2)XMLInputFactory.newInstance();
        XMLEventReader2 reader = (XMLEventReader2)factory.createXMLEventReader(WoodstoxCase.class.getResourceAsStream("student.xml"));
        //添加过滤器
        XMLEventReader2 filterReader = (XMLEventReader2)factory.createFilteredReader(reader, event -> {
            //处理开始节点
            if (event.isStartElement()) {
                return true;
            }
            return false;
        });
        while (filterReader.hasNext()) {
            XMLEvent event = filterReader.nextEvent();
            if (event.isStartElement()) {
                if ("student".equals(event.asStartElement().getName().getLocalPart())) {
                    logger.info("rollno:" + event.asStartElement().getAttributeByName(new QName("", "rollno")).getValue());
                    Attribute attributeTestattr = event.asStartElement().getAttributeByName(new QName("http://www.w3.org/TR/html4/school/", "testattr"));
                    if (attributeTestattr != null) {
                        logger.info("testattr:" + attributeTestattr.getValue());
                    }
                } else if ("firstname".equals(event.asStartElement().getName().getLocalPart())
                        || "lastname".equals(event.asStartElement().getName().getLocalPart())
                        || "nickname".equals(event.asStartElement().getName().getLocalPart())
                        || "marks".equals(event.asStartElement().getName().getLocalPart())) {
                    logger.info(event.asStartElement().getName().getLocalPart() + ":" + filterReader.getElementText());
                } else {
                    continue;
                }

            }
        }
    }

    /**
     * 生成xml
     * @throws Exception
     */
    @Test
    public void toXml() throws Exception {
        XMLOutputFactory2 factory = (XMLOutputFactory2)XMLOutputFactory2.newInstance();
        XMLStreamWriter2 writer = (XMLStreamWriter2)factory.createXMLStreamWriter(System.out);

        writer.writeStartDocument("UTF-8", "1.0");
        writer.writeStartElement("school", "class", "http://www.w3.org/TR/html4/school/");

        //第一个学生
        writer.writeStartElement("school", "student", "http://www.w3.org/TR/html4/school/");
        writer.writeAttribute("rollno", "1");
        writer.writeAttribute("school","http://www.w3.org/TR/html4/school/", "testattr", "test");
        writer.writeStartElement("school", "firstname", "http://www.w3.org/TR/html4/school/");
        writer.writeCharacters("cxx1");
        writer.writeEndElement();
        writer.writeStartElement("lastname");
        writer.writeCharacters("Bob1");
        writer.writeEndElement();
        writer.writeStartElement("nickname");
        writer.writeCharacters("stars1");
        writer.writeEndElement();
        writer.writeStartElement("marks");
        writer.writeCharacters("85");
        writer.writeEndElement();
        writer.writeEndElement();

        //第二个学生
        writer.writeStartElement("student");
        writer.writeAttribute("rollno", "2");
        writer.writeStartElement("firstname");
        writer.writeCharacters("cxx2");
        writer.writeEndElement();
        writer.writeStartElement("lastname");
        writer.writeCharacters("Bob2");
        writer.writeEndElement();
        writer.writeStartElement("nickname");
        writer.writeCharacters("stars2");
        writer.writeEndElement();
        writer.writeStartElement("marks");
        writer.writeCharacters("85");
        writer.writeEndElement();
        writer.writeEndElement();

        //第三个学生
        writer.writeStartElement("student");
        writer.writeAttribute("rollno", "3");
        writer.writeStartElement("firstname");
        writer.writeCharacters("cxx3");
        writer.writeEndElement();
        writer.writeStartElement("lastname");
        writer.writeCharacters("Bob3");
        writer.writeEndElement();
        writer.writeStartElement("nickname");
        writer.writeCharacters("stars3");
        writer.writeEndElement();
        writer.writeStartElement("marks");
        writer.writeCharacters("85");
        writer.writeEndElement();
        writer.writeEndElement();

        writer.writeEndElement();
        writer.writeEndDocument();
    }
}

 

Java操作XML(4)--使用woodstox处理XML

标签:sch   class   efi   filter   html   代码   rac   element   tin   

原文地址:https://www.cnblogs.com/wuyongyin/p/14333642.html


评论


亲,登录后才可以留言!