DOMImplementationLS+LSParserFilter

2010-10-26T00:00:00+09:00 Java

DOM LeveL3のDOMImplemetationLSの使用法メモ

使用するXMLが

<?xml version="1.0" encoding="UTF-8" ?>
<users>
    <user name="hoge" />
    <user name="fuga" />
</users>

<user>のname属性値がhogeのものだけを通過させ新しいXMLファイルを生成する

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSParserFilter;
import org.w3c.dom.ls.LSSerializer;
import org.w3c.dom.traversal.NodeFilter;
import org.apache.xerces.dom.DOMImplementationImpl;

public class Client {

    public static void main(String[] args) {
        DOMImplementationLS impl = new DOMImplementationImpl();
        LSInput in = impl.createLSInput();
        LSOutput out = impl.createLSOutput();
        LSSerializer serializer = impl.createLSSerializer();

        LSParser parser = impl.createLSParser(
            DOMImplementationLS.MODE_SYNCHRONOUS,
            null
        );
        parser.setFilter(new LSParserFilter() {

            @Override
            public short startElement(Element elementArg) {
                return FILTER_ACCEPT;
            }

            @Override
            public int getWhatToShow() {
                return NodeFilter.SHOW_ELEMENT;
            }

            @Override
            public short acceptNode(Node n) {
                if(n.getNodeName().equals("user")) {
                    Element e = (Element)n;

                    if(e.getAttribute("name").equals("hoge"))
                        return FILTER_ACCEPT;
                }

                return FILTER_REJECT;
            }
        });

        try (
            InputStream is = Client.class.getResourceAsStream(("sample.xml"));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ) {
            in.setByteStream(is);

            Document doc = parser.parse(in);

            out.setByteStream(baos);
            serializer.write(doc, out);

            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

壊れかけたハードディスクからデータを抽出する 緯度経度から距離を算出