概述
xml文档的组织形式类似于树的结构,具体阐述在前一篇文章中有阐述 https://blog.csdn.net/weixin_38907330/article/details/80763880
那么在matlab环境下对xml文件进行读写,也就是本着按着节点一级一级访问的形式进行的
1.读xml
首先读入文件:
xml=xmlread('1_2.xml','r');这时读入的xml为一个matlab自己定义的对象,并非结构体
然后开始一级一级对.xml文档进行访问(下面插入的就是示例)
% %<annotation> --------根节点
% <folder>train_data/1</folder> ----图片路径
% <filename>1_2.jpg</filename> ---文件名称
% <size> ----尺寸信息
% <img_width>680</img_width>
% <img_height>571</img_height>
% <img_depth>3</img_depth>
% </size>
% <object> -----目标
% <name>1</name>
% <difficult>0</difficult>
% <bounding_box>
% <x_left_top>75</x_left_top>
% <y_left_top>395</y_left_top>
% <width>164</width>
% <height>175</height>
% </bounding_box>
% </object>
% </annotation>
访问xml有几个关键的操作:获取子节点的数目(getLength),该获取子节点(getChildNodes),访问节点内容(getTextContent),获取节点名称(getNodeName)(对子节点的访问是通过item来进行的)
Nodes=xml.getChildNodes;//xml就是我们之前读入的对象,这一步可以获取xml文档的根节点
RootNOdes=Nodes.item(0) ;//为什么是0呢?因为根节点就只有一个,所以根节点就是item(0)
然后就是要根据xml文档的结构来一级一级的访问,首先访问RootNodes的子节点:
childnodes=RootNodes.item(0).getChildNodes;%解析出各个节点
nodenum=childnodes.getLength;//子节点的数目
for i=0:nodenum-1 %遍历各个节点
str=char(childnodes.item(i).getNodeName);
if(strcmp(str,'folder'))
disp(['folder:' ' ' char(childnodes.item(i).getTextContent)]);
elseif(strcmp(str,'filename'))
disp(['filename:' ' ' char(childnodes.item(i).getTextContent)]);
elseif(strcmp(str,'size'))
showsize(childnodes.item(i));
elseif(strcmp(str,'object'))
showobject(childnodes.item(i));
else
end
end
//因为size节点和object节点又包含子节点,所以我之后写了个函数,使其能继续访问该节点下面的子节点
读取差不多就是这样啦,如果想要实例可以去这里下载:https://download.csdn.net/download/weixin_38907330/10579829
(2018.10.30補充)
xml讀取屬性:
nodes.getAttributes.item(0)//如果有n个属性,那么item可以索引到n-1
2. 写xml文档
主要思路:
- 先创建xml对象,同时初始化xml的根节点名称
- 一级一级的添加节点
- 最后使用xmlwrite将文件对象写入到文档
docNode = com.mathworks.xml.XMLUtils.createDocument('annotation'); //创建一个根节点为annotation的xml文档
docRootNode = docNode.getDocumentElement;%得到文件根节点
需要掌握的几个基本操作,创建节点,向节点里面添加内容,添加节点到父节点
thisnode= docNode.createElement('folder');//创建了一个名为folder的子节点
thisnode.appendChild(docNode.createTextNode(内容));//向thisnode里面添加内容
docRootNode.appendChild(thisnode);//添加到父节点
对于如下局部结构:
<size>
<width>486</width>
<height>500</height>
<depth>3</depth>
</size>
其对应的代码为:
thisnode=docNode.createElement('size');
node1=docNode.createElement('width');
node2=docNode.createElement('height');
node3=docNode.createElement('depth');
node1.appendChild(docNode.createTextNode(width));
node2.appendChild(docNode.createTextNode(height));
node3.appendChild(docNode.createTextNode(depth));
thisnode.appendChild(node1);
thisnode.appendChild(node2);
thisnode.appendChild(node3);
好啦,基本上就是这样,其实思路明确了,几个基本操作了解,再复杂的xml文档也能读写自如
PS:VOC格式标注中,x代表列,y代表行
最后
以上就是平淡溪流为你收集整理的matlab读写xml的全部内容,希望文章能够帮你解决matlab读写xml所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复