Java操作XML文件(2)-读取XML文件

package xml;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
  
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.NodeList;  
  
public class XMLReader {  
    private String fileName;  
  
    public XMLReader(String fileName) {  
        this.fileName = fileName;  
    }  
  
    public Element getRootElement() throws Exception {  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder = factory.newDocumentBuilder();  
        Document document = builder.parse(fileName);  
        return document.getDocumentElement();  
    }  
  
    public List<Element> getElementsByTagName(Element parent, String tagName) {  
        List<Element> elements = new ArrayList<Element>();  
        if (parent != null) {  
            NodeList list = parent.getElementsByTagName(tagName);  
            for (int i = 0; i < list.getLength(); i++) {  
                elements.add((Element) list.item(i));  
            }  
        }  
        return elements;  
    }  
  
    public Element getElementByTagName(Element parent, String tagName, int index) {  
        List<Element> elements = getElementsByTagName(parent, tagName);  
        if (index < 0 || index >= elements.size()) {  
            return elements.get(0);  
        } else {  
            return elements.get(index);  
        }  
    }  
  
    public String getTextContent(Element e) {  
        return e.getTextContent();  
    }  
  
    public String getAttribute(Element e, String name) {  
        return e.getAttribute(name);  
    }  
  
    public static void main(String[] args) {  
        try {  
            XMLReader reader = new XMLReader("E:\\test.xml");  
            Element root = reader.getRootElement();  
            System.out  
                    .println(reader.getElementsByTagName(root, "Book").size());  
            Element book = reader.getElementByTagName(root, "Book", 0);  
            Element price = reader.getElementByTagName(book, "Price", 0);  
            System.out.println(price.getTextContent());  
            Element title = reader.getElementByTagName(book, "Title", 0);  
            System.out.println(reader.getTextContent(title));  
            System.out.println(reader.getAttribute(title, "Auth"));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
    }  
}  

你可能感兴趣的:(java,xml)