자바 재 귀적 XML 모든 요소 옮 겨 다 니 기

3863 단어
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultAttribute;

/**
 * Java    XML    
 * 
 * @author  Administrator
 * @version  [   , Apr 13, 2010]
 * @see  [   /  ]
 * @since  [  /    ]
 */
public class XmlParser
{
    // private static Map xmlmap = new HashMap(); 
    //  xml        
    private static ArrayList elemList = new ArrayList();
    
    public static void main(String args[])
        throws DocumentException
    {
        XmlParser test = new XmlParser();
        String path = "C:/a.xml";
        //   XML  
        SAXReader reader = new SAXReader();
        Document doc = reader.read(path);
        //   XML   
        Element root = doc.getRootElement();
        test.getElementList(root);
        String x = test.getListString(elemList);
        System.out.println("-----------    ------------
" + x); } /** * * * @param element * @return * @see [ 、 # 、 # ] */ public String getNoteAttribute(Element element) { String xattribute = ""; DefaultAttribute e = null; List list = element.attributes(); for (int i = 0; i < list.size(); i++) { e = (DefaultAttribute)list.get(i); //System.out.println("name = " + e.getName() + ", value = " + e.getText()); xattribute += " [name = " + e.getName() + ", value = " + e.getText() + "]"; } return xattribute; } /** * * * @param element * @see [ 、 # 、 # ] */ public void getElementList(Element element) { List elements = element.elements(); // if (elements.isEmpty()) { String xpath = element.getPath(); String value = element.getTextTrim(); elemList.add(new Leaf(getNoteAttribute(element), xpath, value)); } else { // Iterator it = elements.iterator(); while (it.hasNext()) { Element elem = (Element)it.next(); // getElementList(elem); } } } public String getListString(List elemList) { StringBuffer sb = new StringBuffer(); for (Iterator it = elemList.iterator(); it.hasNext();) { Leaf leaf = (Leaf)it.next(); sb.append("xpath: " + leaf.getXpath()).append(", value: ").append(leaf.getValue()); if (!"".equals(leaf.getXattribute())) { sb.append(", Attribute: ").append(leaf.getXattribute()); } sb.append("
"); } return sb.toString(); } } /** * xml */ class Leaf { // private String xattribute; // PATH private String xpath; // private String value; public Leaf(String xattribute, String xpath, String value) { this.xattribute = xattribute; this.xpath = xpath; this.value = value; } public String getXpath() { return xpath; } public void setXpath(String xpath) { this.xpath = xpath; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getXattribute() { return xattribute; } public void setXattribute(String xattribute) { this.xattribute = xattribute; } }

좋은 웹페이지 즐겨찾기