程序员

SAX解析及修改xml

2020-10-09  本文已影响0人  世外大帝

修改xml,通常不会全篇修改,只修改某些关键节点

解析

用到的实体类

public class RadarSetEntity {
    private String signSpeed;
    private String speedLimit;
    private String bigCarSignSpeed;
    private String bigCarSpeedLimit;
    private String radarConstantCorrection;

    public String getRadarConstantCorrection() {
        return radarConstantCorrection;
    }

    public void setRadarConstantCorrection(String radarConstantCorrection) {
        this.radarConstantCorrection = radarConstantCorrection;
    }

    public String getSignSpeed() {
        return signSpeed;
    }

    public void setSignSpeed(String signSpeed) {
        this.signSpeed = signSpeed;
    }

    public String getSpeedLimit() {
        return speedLimit;
    }

    public void setSpeedLimit(String speedLimit) {
        this.speedLimit = speedLimit;
    }

    public String getBigCarSignSpeed() {
        return bigCarSignSpeed;
    }

    public void setBigCarSignSpeed(String bigCarSignSpeed) {
        this.bigCarSignSpeed = bigCarSignSpeed;
    }

    public String getBigCarSpeedLimit() {
        return bigCarSpeedLimit;
    }

    public void setBigCarSpeedLimit(String bigCarSpeedLimit) {
        this.bigCarSpeedLimit = bigCarSpeedLimit;
    }
}

获取解析文件

    private static RadarSetEntity requestRadarData() {
        File file = new File(SetRadarFragment.radar_path);
        if (file.exists()) {
            return XmlUtils.readRadarSetEntityBySax(file);
        } else {
            L.e("文件为空");
        }
        return null;
    }

发起解析

    public static RadarSetEntity readRadarSetEntityBySax(File file) {
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser saxParser = spf.newSAXParser();
            RadarGetHandler handler = new RadarGetHandler();
            saxParser.parse(file, handler);
            return handler.getRadarSetEntity();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

解析过程

package com.ahsoft.tachymeterapp.utils.xml;

import com.ahsoft.tachymeterapp.model.entity.RadarSetEntity;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

/**
 * created by Taoyuan on 2020/9/4
 * RadarSet xml 内容处理
 */
public class RadarGetHandler extends DefaultHandler {

    private String tagName = null;//当前解析的元素标签
    private RadarSetEntity radarSet;
    private int laneId = 0;

    RadarSetEntity getRadarSetEntity() {
        return radarSet;
    }


    /**
     * 文档开始
     **/
    @Override
    public void startDocument() {
        radarSet = new RadarSetEntity();
    }


    /**
     * 标签开始
     *
     * @param uri        命名空间
     * @param localName  元素本地名称(不带前缀)
     * @param qName      元素的限定名(带前缀)
     * @param attributes 元素属性
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) {
        this.tagName = localName;
    }

    /**
     * 接收标签中的字符数据
     *
     * @param ch     存放标签中的内容
     * @param start  起始位置
     * @param length 内容长度
     */
    @Override
    public void characters(char[] ch, int start, int length) {
        if (tagName != null) {
            String value = new String(ch, start, length);
            switch (tagName) {
                case "laneId": // 车道标识
                    laneId = Integer.parseInt(value);
                    break;
                case "signSpeed": // 30
                    if (laneId == 1) {
                        radarSet.setSignSpeed(value);
                    }
                    break;
                case "speedLimit": // 33
                    if (laneId == 1) {
                        radarSet.setSpeedLimit(value);
                    }
                    break;
                case "bigCarSignSpeed":// 30
                    if (laneId == 1) {
                        radarSet.setBigCarSignSpeed(value);
                    }
                    break;
                case "bigCarSpeedLimit":// 33
                    if (laneId == 1) {
                        radarSet.setBigCarSpeedLimit(value);
                    }
                    break;
                case "radarConstantCorrection":// 雷达常量校正系数
                    if (laneId == 1) {
                        radarSet.setRadarConstantCorrection(value);
                    }
                    break;
            }
        }
    }


    /**
     * 标签结束
     *
     * @param uri       命名空间
     * @param localName 元素本地名称(不带前缀)
     * @param qName     元素的限定名(带前缀)
     */
    @Override
    public void endElement(String uri, String localName, String qName) {
        this.tagName = null;
    }


}

修改

发起解析

    public static File writeRadarSetEntityBySax(File file, RadarSetEntity radarSetEntity) {
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser saxParser = spf.newSAXParser();
            RadarSetHandler handler = new RadarSetHandler(radarSetEntity);
            saxParser.parse(file, handler);
            return handler.getFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

解析过程

package com.ahsoft.tachymeterapp.utils.xml;

import com.ahsoft.tachymeterapp.model.entity.RadarSetEntity;
import com.ahsoft.tachymeterapp.view.fragment.SetRadarFragment;
import com.jty.myutils.utils.FileUtils;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

/**
 * created by Taoyuan on 2020/9/30
 * RadarSet xml 内容处理
 */
public class RadarSetHandler extends DefaultHandler {

    private String tagName = null;//当前解析的元素标签
    private TransformerHandler writeHandler; // 写文档
    private File file; //要写出的文件
    private RadarSetEntity radarSet; // 要变更的实体类
    private int laneId = 0;

    public RadarSetHandler(RadarSetEntity radarSetEntity) {
        file = new File(SetRadarFragment.radar_put_path);
        FileUtils.createOrExistsFile(file);
        radarSet = radarSetEntity;
    }

    /**
     * 返回写完的文件
     *
     * @return 写完的文件
     */
    public File getFile() {
        return file;
    }

    /**
     * 文档开始
     **/
    @Override
    public void startDocument() throws SAXException {
        // prepare
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        try {
            this.writeHandler = transformerFactory.newTransformerHandler();
            Transformer transformer = writeHandler.getTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            StreamResult streamResult = new StreamResult(new FileOutputStream(file));
            this.writeHandler.setResult(streamResult);
        } catch (IOException | TransformerConfigurationException e) {
            e.printStackTrace();
        }

        // begin
        this.writeHandler.startDocument();
    }


    /**
     * 标签开始
     *
     * @param uri        命名空间
     * @param localName  元素本地名称(不带前缀)
     * @param qName      元素的限定名(带前缀)
     * @param attributes 元素属性
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        this.tagName = localName;
        this.writeHandler.startElement(uri, localName, qName, attributes);
    }

    /**
     * 接收标签中的字符数据
     *
     * @param ch     存放标签中的内容
     * @param start  起始位置
     * @param length 内容长度
     */
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (tagName != null) {
            char[] ch2 = null;
            String all = new String(ch, 0, ch.length);
            StringBuilder sb = new StringBuilder();
            String value = new String(ch, start, length);
            switch (tagName) {
                case "laneId": //车道标识
                    laneId = Integer.parseInt(value);
                    break;
                case "signSpeed": // 30
                    if (laneId == 1) {
                        sb.append(all.substring(0, start).concat(radarSet.getSignSpeed()));
                        ch2 = sb.toString().toCharArray();
                    }
                    break;
                case "speedLimit": // 33
                    if (laneId == 1) {
                        sb.append(all.substring(0, start).concat(radarSet.getSpeedLimit()));
                        ch2 = sb.toString().toCharArray();
                    }
                    break;
                case "bigCarSignSpeed":// 30
                    if (laneId == 1) {
                        sb.append(all.substring(0, start).concat(radarSet.getBigCarSignSpeed()));
                        ch2 = sb.toString().toCharArray();
                    }
                    break;
                case "bigCarSpeedLimit":// 33
                    if (laneId == 1) {
                        sb.append(all.substring(0, start).concat(radarSet.getBigCarSpeedLimit()));
                        ch2 = sb.toString().toCharArray();
                    }
                    break;
                case "radarConstantCorrection":// 雷达常量校正系数
                    if (laneId == 1) {
                        sb.append(all.substring(0, start).concat(radarSet.getRadarConstantCorrection()));
                        ch2 = sb.toString().toCharArray();
                    }
                    break;
            }

            if (ch2 != null) {
                this.writeHandler.characters(ch2, start, length);
            } else {
                this.writeHandler.characters(ch, start, length);
            }
        }
    }


    /**
     * 标签结束
     *
     * @param uri       命名空间
     * @param localName 元素本地名称(不带前缀)
     * @param qName     元素的限定名(带前缀)
     */
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        this.tagName = null;
        this.writeHandler.endElement(uri, localName, qName);
    }

    /**
     * 文档结束
     **/
    @Override
    public void endDocument() throws SAXException {
        this.writeHandler.endDocument();
    }


}

上一篇下一篇

猜你喜欢

热点阅读