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 (ParserConfigurationExcep tion 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;
    };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值