android下使用dom讀寫xml文件

上篇我們使用XmlSerializer創建的xml文件,發現了些問題,那樣的xml文件是不標準的,只能自己創建自己讀,而不能供給譬如opencv的FileStorage來讀取。而且,opencv能夠讀取的xml文件還有着其他嚴格的格式控制,下面簡單介紹一下。如下所示:
 
<?xml version="1.0" encoding="utf-8"?>
<opencv_storage>
<person>
<_>
<x>90</x>
</_>
</person>
</opencv_storage>

其中:<opencv_storage>是必須要有的,貌似是一個標誌神馬,<_>也是必須要有的,也是一個神馬標誌。我通過以下c++程序來讀取一個這樣的xml文件:

FileStorage fs("b.xml", FileStorage::READ);
if (fs.isOpened())
{
FileNode dbName = fs["person"];
int age;
string strName;
FileNodeIterator it = dbName.begin(), it_end = dbName.end();

for( size_t i = 0; it != it_end; ++it, i++ )
{
(*it)["name"]>>strName;
cout<<strName <<endl;
(*it)["x"] >>age ;
cout<<age<<endl;
(*it)["y"] >>age ;
cout<<age<<endl;
}
fs.release();
}

是不是很簡單,opencv 讀取xml文件就是這麼簡單!

下面來看一下如何創建通用的xml文件:

    private void createXmlFile(List<coordinate> Items,OutputStream out){  
        
        try {  
            DocumentBuilderFactory factory = DocumentBuilderFactory  
                    .newInstance();  
            DocumentBuilder builder = factory.newDocumentBuilder();  
            Document doc  = builder.newDocument();  
 
            Element rootEle = doc.createElement_x_x_x_x_x("opencv_storage");  
            doc.a(rootEle);  

            Element groupEle = doc.createElement_x_x_x_x_x("person");  

            for (coordinate Item : Items)
            {
           Element personEle1 = doc.createElement_x_x_x_x_x("_");
           
           Element chinese0 = doc.createElement_x_x_x_x_x("name");  
           chinese0.a(doc.createTextNode(String.valueOf(Item.getName())));  
           personEle1.a(chinese0);   
           
           Element chinese1 = doc.createElement_x_x_x_x_x("x");  
           chinese1.a(doc.createTextNode(String.valueOf(Item.getX())));  
           personEle1.a(chinese1);                       
            
           Element chinese2 = doc.createElement_x_x_x_x_x("y");  
           chinese2.a(doc.createTextNode(String.valueOf(Item.getY())));  
           personEle1.a(chinese2);
           groupEle.a(personEle1);
            } 
            rootEle.a(groupEle);             
              
            TransformerFactory tf = TransformerFactory.newInstance();  
            Transformer transformer = tf.newTransformer();  
              
            DOMSource source = new DOMSource(doc);  
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");  
            transformer.setOutputProperty(OutputKeys.INDENT, "no");  

            PrintWriter pw = new PrintWriter(out);  
            StreamResult result = new StreamResult(pw);  
            transformer.transform(source, result);  
              
            System.out.println("生成XML文件成功!");  
        } catch (ParserConfigurationException e) {  
            System.out.println(e.getMessage());  
        } catch (TransformerException e) {  
            System.out.println(e.getMessage());  
        } 
          
    }  

這個就是創建上述xml文件的程序。使用的是dom來創建的。
其中的coordinate類如下:

public class coordinate {
private Integer id;  
    private String name;  
    private int x;  
    private int y;
      
    public coordinate ()  
    {}  
    public coordinate (String name ,int x,int y)  
    {  
        this.name = name;  
        this.x = x;  
        this.y = y;
    }  
    public Integer getId() {  
        return id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getX() {  
        return x;  
    }  
    public void setX(int x) {  
        this.x = x;  
    }  
    public int getY() {  
        return y;  
    }  
    public void setY(int y) {  
        this.y = y;  
    }  
    @Override  
    public String toString() {  
        // TODO Auto-generated method stub  
        return this.id+",name  "+this.name+"  X  "+this.x+"  Y  "+this.y+"\n";  
    }  

}

我們只需要通過這樣一條語句就可以創建出需要的xml文件了。//list1中存放創建的內容
createXmlFile(list1,new FileOutputStream(new File("/sdcard/data","c.xml")));



下面順便放上通過dom解析(讀取)xml文件的程序供大家參考:

    public List<coordinate> XMLReader(InputStream inStream) throws Exception{
      List<coordinate> persons=new ArrayList<coordinate>();
      DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
      try{
       DocumentBuilder builder=factory.newDocumentBuilder();
       Document document= builder.parse(inStream);
       Element root=document.getDocumentElement();
       NodeList items=root.getElementsByTagName_r("_");
       for(int i=0;i<items.getLength();i++)
       {
        coordinate person=new coordinate();
        Element personNode=(Element)items.item(i);

        NodeList childsNodes = personNode.getChildNodes();
         for (int j = 0; j < childsNodes.getLength(); j++) 
         {
         Node node = (Node) childsNodes.item(j);   
         if(node.getNodeType() == Node.ELEMENT_NODE)
         {        
         Element childNode = (Element) node;

         if ("name".equals(childNode.getNodeName())) {
      
            person.setName(childNode.getFirstChild().getNodeValue());
         } 
         else if ("x".equals(childNode.getNodeName())) 
         {
            person.setX(new Short(childNode.getFirstChild().getNodeValue()));
         }
         else if ("y".equals(childNode.getNodeName())) 
         {
            person.setY(new Short(childNode.getFirstChild().getNodeValue()));
         }
         }
          }
          persons.add(person);
        }
        inStream.close();             
      }catch(Exception e){
       e.printStackTrace();         
      }
      return persons;
    };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章