【问题标题】:Easy way to read XML file读取 XML 文件的简单方法
【发布时间】:2015-04-30 07:33:32
【问题描述】:

我有一个这样的 XML 文件

<persons>
<person>
<name>Joe</name>
<age>44</age>
</person>
</persons>

我想知道一种简单的阅读方法。 我用我的代码制作了这个 xml 文件

XmlSerializer serializador = Xml.newSerializer();

try{
    FileOutputStream file= openFileOutput("ff.xml",MODE_PRIVATE);
    serializador.setOutput(ff, "UTF-8");

    serializador.startDocument("UTF-8", true);
    serializador.startTag("", "persons");

    serializador.startTag("","person");
    serializador.text("joe");
    serializador.endTag("","person");

    serializador.startTag("","age");
    serializador.text("44");
    serializador.endTag("","age");

    serializador.endTag("", "persons");
    serializador.endDocument();

    Toast.makeText(this,"XML OK",Toast.LENGTH_SHORT).show();
}catch (Exception ex){
    txt1.setText(ex.toString());

}

现在我需要一个简单的方法来阅读它......以及如何将此文件保存在/myDir/here/ff.xml 之类的路径中 不在data/data/my_app/files

【问题讨论】:

    标签: android xml parsing


    【解决方案1】:

    您可以使用Simple 框架。我以前用过它,很高兴它做得很好。试试看,你不会后悔的:)

    【讨论】:

    • 如果您将其作为评论而不是答案发布,对您来说会更合适。
    【解决方案2】:

    除了手动上去阅读,你可以使用XML Pull Parser或者你也可以试试SAX Parser

    【讨论】:

    • 如果您将其作为评论而不是答案发布,对您来说会更合适。
    【解决方案3】:

    读取 XML-Files 基本上有两种方法:

    1. 使用 DOM 接口,这意味着将整个文档对象模型读入内存。
    2. 使用 SAX 接口意味着在读取 XML 文件的同时对其进行处理。 (适合大文件)

    如果您有一个 XML 文件,例如列出三个员工,如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
    <Personnel>
       <Employee type="permanent">
            <Name>Seagull</Name>
            <Id>3674</Id>
            <Age>34</Age>
       </Employee>
      <Employee type="contract">
            <Name>Robin</Name>
            <Id>3675</Id>
            <Age>25</Age>
        </Employee>
      <Employee type="permanent">
            <Name>Crow</Name>
            <Id>3676</Id>
            <Age>28</Age>
        </Employee>
    </Personnel>
    

    您可以使用以下代码将其读入相应的员工类:

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    public class DomParserExample {
    
        //No generics
        List myEmpls;
        Document dom;
    
    
        public DomParserExample(){
            //create a list to hold the employee objects
            myEmpls = new ArrayList();
        }
    
        public void runExample() {
    
            //parse the xml file and get the dom object
            parseXmlFile();
    
            //get each employee element and create a Employee object
            parseDocument();
    
            //Iterate through the list and print the data
            printData();
    
        }
    
    
        /* (1) Get a document builder using document builder factory and 
         * parse the xml file to create a DOM object
         */
        private void parseXmlFile(){
            //get the factory
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    
            try {
    
                //Using factory get an instance of document builder
                DocumentBuilder db = dbf.newDocumentBuilder();
    
                //parse using builder to get DOM representation of the XML file
                dom = db.parse("employees.xml");
    
    
            }catch(ParserConfigurationException pce) {
                pce.printStackTrace();
            }catch(SAXException se) {
                se.printStackTrace();
            }catch(IOException ioe) {
                ioe.printStackTrace();
            }
        }
    
        /* (2) Get a list of employee elements:
         *  Get the rootElement from the DOM object.
         *  From the root element get all employee elements. 
         *  Iterate through each employee element to load the data.
         */     
        private void parseDocument(){
            //get the root elememt
            Element docEle = dom.getDocumentElement();
    
            //get a nodelist of <employee> elements
            NodeList nl = docEle.getElementsByTagName("Employee");
    
            if(nl != null && nl.getLength() > 0) {
                for(int i = 0 ; i < nl.getLength();i++) {
    
                    //get the employee element
                    Element el = (Element)nl.item(i);
    
                    //get the Employee object
                    Employee e = getEmployee(el);
    
                    //add it to list
                    myEmpls.add(e);
                }
            }
        }
    
    
        /**
         * (3)For each employee element get the id,name,age and type. 
         * Create an employee value object and add it to the list.
         *  I take an employee element and read the values in, create
         * an Employee object and return it
         * @param empEl
         * @return
         */
        private Employee getEmployee(Element empEl) {
    
            //for each <employee> element get text or int values of 
            //name ,id, age and type
            String name = getTextValue(empEl,"Name");
            int id = getIntValue(empEl,"Id");
            int age = getIntValue(empEl,"Age");
    
            String type = empEl.getAttribute("type");
    
            //Create a new Employee with the value read from the xml nodes
            Employee e = new Employee(name,id,age,type);
    
            return e;
        }
    
    
        /**
         * I take a xml element and the tag name, look for the tag and get
         * the text content 
         * i.e for <employee><name>John</name></employee> xml snippet if
         * the Element points to employee node and tagName is name I will return John  
         * @param ele
         * @param tagName
         * @return
         */
        private String getTextValue(Element ele, String tagName) {
            String textVal = null;
            NodeList nl = ele.getElementsByTagName(tagName);
            if(nl != null && nl.getLength() > 0) {
                Element el = (Element)nl.item(0);
                textVal = el.getFirstChild().getNodeValue();
            }
    
            return textVal;
        }
    
    
        /**
         * Calls getTextValue and returns a int value
         * @param ele
         * @param tagName
         * @return
         */
        private int getIntValue(Element ele, String tagName) {
            //in production application you would catch the exception
            return Integer.parseInt(getTextValue(ele,tagName));
        }
    
        /**
         * Iterate through the list and print the 
         * content to console
         */
        private void printData(){
    
            System.out.println("No of Employees '" + myEmpls.size() + "'.");
    
            Iterator it = myEmpls.iterator();
            while(it.hasNext()) {
                System.out.println(it.next().toString());
            }
        }
    
    
        public static void main(String[] args){
            //create an instance
            DomParserExample dpe = new DomParserExample();
    
            //call run example
            dpe.runExample();
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多