⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myxmlmemento.java

📁 eclipse开发笔记
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package com.plugindev.addressbook.editors.models;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.ui.IMemento;
import org.eclipse.ui.WorkbenchException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class MYXMLMemento implements IMemento {
    private Document factory;

    private Element element;

    /**
     * Creates a <code>Document</code> from the <code>Reader</code>
     * and returns a memento on the first <code>Element</code> for reading
     * the document.
     * <p>
     * Same as calling createReadRoot(reader, null)
     * </p>
     * 
     * @param reader the <code>Reader</code> used to create the memento's document
     * @return a memento on the first <code>Element</code> for reading the document
     * @throws WorkbenchException if IO problems, invalid format, or no element.
     */
    public static MYXMLMemento createReadRoot(Reader reader)
            throws WorkbenchException {
        return createReadRoot(reader, null);
    }

    /**
     * Creates a <code>Document</code> from the <code>Reader</code>
     * and returns a memento on the first <code>Element</code> for reading
     * the document.
     * 
     * @param reader the <code>Reader</code> used to create the memento's document
     * @param baseDir the directory used to resolve relative file names
     * 		in the XML document. This directory must exist and include the
     * 		trailing separator. The directory format, including the separators,
     * 		must be valid for the platform. Can be <code>null</code> if not
     * 		needed.
     * @return a memento on the first <code>Element</code> for reading the document
     * @throws WorkbenchException if IO problems, invalid format, or no element.
     */
    public static MYXMLMemento createReadRoot(Reader reader, String baseDir)
            throws WorkbenchException {
        String errorMessage = null;
        Exception exception = null;

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            InputSource source = new InputSource(reader);
            if (baseDir != null) {
				source.setSystemId(baseDir);
			}
            Document document = parser.parse(source);
            NodeList list = document.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                if (node instanceof Element) {
					return new MYXMLMemento(document, (Element) node);
				}
            }
        } catch (ParserConfigurationException e) {
            exception = e;
            errorMessage = "Internal XML parser configuration error.";
        } catch (IOException e) {
            exception = e;
            errorMessage = "Could not read content of XML file."; 
        } catch (SAXException e) {
            exception = e;
            errorMessage = "Could not parse content of XML file."; 
        }

        String problemText = null;
        if (exception != null) {
			problemText = exception.getMessage();
		}
        if (problemText == null || problemText.length() == 0) {
			problemText = errorMessage != null ? errorMessage
                    : "Could not find root element node of XML file.";
		} 
        throw new WorkbenchException(problemText, exception);
    }

    /**
     * Returns a root memento for writing a document.
     * 
     * @param type the element node type to create on the document
     * @return the root memento for writing a document
     */
    public static MYXMLMemento createWriteRoot(String type) {
        Document document;
        try {
            document = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder().newDocument();
            Element element = document.createElement(type);
            document.appendChild(element);
            return new MYXMLMemento(document, element);
        } catch (ParserConfigurationException e) {
//            throw new Error(e);
            throw new Error(e.getMessage());
        }
    }

    /**
     * Creates a memento for the specified document and element.
     * <p>
     * Clients should use <code>createReadRoot</code> and
     * <code>createWriteRoot</code> to create the initial
     * memento on a document.
     * </p>
     * 
     * @param document the document for the memento
     * @param element the element node for the memento
     */
    public MYXMLMemento(Document document, Element element) {
        super();
        this.factory = document;
        this.element = element;
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public IMemento createChild(String type) {
        Element child = factory.createElement(type);
        element.appendChild(child);
        return new MYXMLMemento(factory, child);
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public IMemento createChild(String type, String id) {
        Element child = factory.createElement(type);
        child.setAttribute(TAG_ID, id == null ? "" : id); //$NON-NLS-1$
        element.appendChild(child);
        return new MYXMLMemento(factory, child);
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public IMemento copyChild(IMemento child) {
        Element childElement = ((MYXMLMemento) child).element;
        Element newElement = (Element) factory.importNode(childElement, true);
        element.appendChild(newElement);
        return new MYXMLMemento(factory, newElement);
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public IMemento getChild(String type) {

        // Get the nodes.
        NodeList nodes = element.getChildNodes();
        int size = nodes.getLength();
        if (size == 0) {
			return null;
		}

        // Find the first node which is a child of this node.
        for (int nX = 0; nX < size; nX++) {
            Node node = nodes.item(nX);
            if (node instanceof Element) {
                Element element = (Element) node;
                if (element.getNodeName().equals(type)) {
					return new MYXMLMemento(factory, element);
				}
            }
        }

        // A child was not found.
        return null;
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public IMemento[] getChildren(String type) {

        // Get the nodes.
        NodeList nodes = element.getChildNodes();
        int size = nodes.getLength();
        if (size == 0) {
			return new IMemento[0];
		}

        // Extract each node with given type.
        ArrayList list = new ArrayList(size);
        for (int nX = 0; nX < size; nX++) {
            Node node = nodes.item(nX);
            if (node instanceof Element) {
                Element element = (Element) node;
                if (element.getNodeName().equals(type)) {
					list.add(element);
				}
            }
        }

        // Create a memento for each node.
        size = list.size();
        IMemento[] results = new IMemento[size];
        for (int x = 0; x < size; x++) {
            results[x] = new MYXMLMemento(factory, (Element) list.get(x));
        }
        return results;
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public Float getFloat(String key) {
        Attr attr = element.getAttributeNode(key);
        if (attr == null) {
			return null;
		}
        String strValue = attr.getValue();
        try {
            return new Float(strValue);
        } catch (NumberFormatException e) {
            System.out.println("Memento problem - Invalid float for key: " //$NON-NLS-1$
                    + key + " value: " + strValue); //$NON-NLS-1$
            e.printStackTrace();
            return null;
        }
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public String getID() {
        return element.getAttribute(TAG_ID);
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public Integer getInteger(String key) {
        Attr attr = element.getAttributeNode(key);
        if (attr == null) {
			return null;
		}
        String strValue = attr.getValue();
        try {
            return new Integer(strValue);
        } catch (NumberFormatException e) {
        	System.out.println("Memento problem - invalid integer for key: " + key
                    + " value: " + strValue);
        	e.printStackTrace();
        	return null;
        }
    }

    /* (non-Javadoc)
     * Method declared in IMemento.
     */
    public String getString(String key) {
        Attr attr = element.getAttributeNode(key);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -