`
bask
  • 浏览: 144245 次
  • 性别: Icon_minigender_1
  • 来自: 宇宙
社区版块
存档分类
最新评论

DOM XML解析 删除

阅读更多
import java.util.HashMap;
import java.util.Map;

/**
 * 属性值类,描述页面动态表单域信息
 *
 * 
 */
public class AttributeVO implements java.io.Serializable {
    private static final long serialVersionUID = -8683922528577545017L;
    public static enum Sort {
        ASC, DESC
    }

    /**
     * id
     */
    private String id;
    /**
     * 字段名
     */
    private String name;
    /**
     * 控件类型
     */
    private String type;
    /**
     * 描述
     */
    private String description;
    /**
     * 默认值
     */
    private String value;
    /**
     * 码表Code
     */
    private String codeId;
    /**
     * 正则
     */
    private String regex;
    /**
     * 排序
     */
    private String order;

    /**
     * Select下拉数据
     */
    private Map<String, String> select = new HashMap<String, String>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getCodeId() {
        return codeId;
    }

    public void setCodeId(String codeId) {
        this.codeId = codeId;
    }

    public String getRegex() {
        return regex;
    }

    public void setRegex(String regex) {
        this.regex = regex;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public Map<String, String> getSelect() {
        return select;
    }

    public void setSelect(Map<String, String> select) {
        this.select = select;
    }
}


import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.util.*;

/**
 * Date: 2010-4-4
 * Time: 22:39:55
 */
public class AttributeVOXMLUtil {

    public static Map<String, Map<String, AttributeVO>> attributeMap = new HashMap<String, Map<String, AttributeVO>>();

    /**
     * 解析XML
     *
     * @param xmlName
     * @return
     * 
     */
    private static Document getDocument(String xmlName) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = null;
        try {
            document = db.parse(new FileInputStream(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + xmlName)));
        } catch (IOException e) {
            throw new XMLParserException("XML文件没有找到", e);
        } catch (SAXException e) {
            throw new XMLParserException("XML解析错误");
        }
        return document;
    }

    /**
     * 根据Path返回节点列表
     *
     * @param document
     * @param xPath
     * @return
     * 
     */
    private static NodeList getNodeList(Document document, String xPath) {
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        NodeList nodeList = null;
        try {
            nodeList = (NodeList) xpath.evaluate(xPath, document, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            throw new XMLParserException("XPath错误");
        }
        return nodeList;
    }

    /**
     * 根据Path返回单个节点
     *
     * @param document
     * @param xPath
     * @return
     * 
     */
    private static Node getNode(Document document, String xPath) {
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Node node = null;
        try {
            node = (Node) xpath.evaluate(xPath, document, XPathConstants.NODE);
        } catch (XPathExpressionException e) {
            throw new XMLParserException("XPath错误");
        }
        return node;
    }

    /**
     * 根据id删除节点
     *
     * @param xmlName
     * @param itemId
     */
    private static void removeNode(String xmlName, String itemId) {
        Document document = getDocument(xmlName);
        Element root, attributeItem;
        root = document.getDocumentElement();
        attributeItem = (Element) getNode(document, "//attributeItem[@id='" + itemId + "']");
        if (attributeItem != null) {
            //删除一个节点
            root.removeChild(attributeItem);
            //写入到xml
            writeXml(document, xmlName);
            //删除缓存中的Map
            attributeMap.remove(itemId);
        }
    }

    /**
     * 写入XML
     *
     * @param doc
     * @param xmlName
     */
    private static void writeXml(Document doc, String xmlName) {
        OutputStream fileoutputStream = null;
        try {
            fileoutputStream = new FileOutputStream(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + xmlName));
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fileoutputStream);
            transformer.transform(source, result);
        } catch (FileNotFoundException e) {
            throw new XMLParserException("没有找到XML文件", e);
        } catch (TransformerConfigurationException e) {
            throw new XMLParserException("文件写入错误", e);
        } catch (TransformerException e) {
            throw new XMLParserException("文件写入错误", e);
        } finally {
            if (fileoutputStream != null)
                try {
                    fileoutputStream.close();
                } catch (IOException e) {
                    throw new XMLParserException("文件流错误");
                }
        }
    }

    /**
     * 返回信息
     *
     * @param xmlName
     * @return
     * 
     */
    public static Map<String, Map<String, AttributeVO>> queryParserXml(String xmlName) {
        Document document = getDocument(xmlName);
        document.normalize();
        NodeList attributeItemList = getNodeList(document, "//attributeItem");
        int itemLen = attributeItemList.getLength();
        for (int i = 0; i < itemLen; i++) {
            Element element = (Element) attributeItemList.item(i);
            attributeMap.put(element.getAttribute("id"), getAttributeVOMap(document, "//attributeItem[@id='" + element.getAttribute("id") + "']/attribute"));
        }
        return attributeMap;
    }

    /**
     * 封装AttributeItem信息
     *
     * @param document
     * @param xPath
     * @return
     * 
     */
    private static Map<String, AttributeVO> getAttributeVOMap(Document document, String xPath) {
        Map<String, AttributeVO> attributeVOMap = new HashMap<String, AttributeVO>();
        NodeList attributeItemList = getNodeList(document, xPath);
        int itemLen = attributeItemList.getLength();
        for (int i = 0; i < itemLen; i++) {
            Element element = (Element) attributeItemList.item(i);
            attributeVOMap.put(element.getAttribute("name"), getAttributeVO(element, document, xPath + "[@id='" + element.getAttribute("id") + "']/select"));
        }
        return attributeVOMap;
    }

    /**
     * 返回AttributeVO信息
     *
     * @param element
     * @param document
     * @param xPath
     * @return
     * 
     */
    private static AttributeVO getAttributeVO(Element element, Document document, String xPath) {
        Map<String, String> selectMap = new HashMap<String, String>();
        AttributeVO attributeVO = new AttributeVO();
        NodeList attributeItemList = getNodeList(document, xPath);
        int itemLen = attributeItemList.getLength();
        for (int i = 0; i < itemLen; i++) {
            Element selectElement = (Element) attributeItemList.item(i);
            selectMap.put(selectElement.getAttribute("id"), selectElement.getAttribute("value"));
        }
        attributeVO.setId(element.getAttribute("id"));
        attributeVO.setName(element.getAttribute("name"));
        attributeVO.setType(element.getAttribute("type"));
        attributeVO.setDescription(element.getAttribute("description"));
        attributeVO.setValue(element.getAttribute("value"));
        attributeVO.setCodeId(element.getAttribute("codeId"));
        attributeVO.setRegex(element.getAttribute("regex"));
        attributeVO.setOrder(element.getAttribute("order"));
        attributeVO.setSelect(selectMap);
        return attributeVO;
    }

    /**
     * 返回AttributeVO列表
     *
     * @param itemId
     * @return
     * 
     * @see
     */
    public static List<AttributeVO> queryAttribute(final String itemId) {
        return queryAttribute(itemId, AttributeVO.Sort.ASC);
    }

    /**
     * 返回AttributeVO列表
     *
     * @param itemId
     * @param sort
     * @return
     * 
     * @see
     */
    public static List<AttributeVO> queryAttribute(final String itemId, final AttributeVO.Sort sort) {
        final List<AttributeVO> attributeVOList = new LinkedList<AttributeVO>();
        final Map<String, AttributeVO> attributeVOMap = attributeMap.get(itemId);
        if (attributeVOMap != null) {
            final Iterator<String> iterName = attributeVOMap.keySet().iterator();
            while (iterName.hasNext()) {
                attributeVOList.add(attributeVOMap.get(iterName.next()));
            }
            //排序
            Collections.sort(attributeVOList, new Comparator<AttributeVO>() {
                @Override
                public int compare(AttributeVO o1, AttributeVO o2) {
                    final AttributeVO AttributeVO1 = o1;
                    final AttributeVO AttributeVO2 = o2;
                    final Integer order1 = Integer.valueOf(AttributeVO1.getOrder());
                    final Integer order2 = Integer.valueOf(AttributeVO2.getOrder());
                    if (sort.equals(AttributeVO.Sort.ASC))
                        return order1 < order2 ? 0 : 1;
                    else
                        return order1 < order2 ? 1 : 0;
                }
            });
        }
        return attributeVOList;
    }

    /**
     * 根据itemId删除元素
     *
     * @param itemId
     */
    public static void removeItem(String itemId) {
        removeNode("attribute.xml", itemId);
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics