dom4J解析xml

package org.zhang.util.dom4j;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.util.*;

public class Question
{
    
    public List<Element> getElementByURL(String url)
    {
        List<Element> list = new ArrayList<Element>();
        SAXReader reader = new SAXReader();
        Document document = null;
        try
        {
            document = reader.read(url);
        }
        catch (DocumentException e)
        {
            e.printStackTrace();
        }
        return getElementList(document.getRootElement().elements(), list);
    }
    
    private List<Element> getElementList(List<Element> elements, List<Element> list)
    {
        for (Element element : elements)
        {
            if (element.elements().size() == 0)
            {
                list.add(element);
            }
            else if (element.elements().size() > 0)
            {
                getElementList(element.elements(), list);
            }
        }
        return list;
    }
    
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        Question xd = new Question();
        String url = "Question.xml";
        List<Element> list = xd.getElementByURL(url);
        for (int i = 0; i < list.size(); i++)
        {
            System.out.print(list.get(i).getName());
            System.out.print(" : ");
            System.out.println(list.get(i).getStringValue());
        }
        
    }
    
}

 

你可能感兴趣的:(xml)