从MATLAB中解析xml

时间:2013-11-27 07:14:05

标签: xml matlab

<root>
   <file name="C:\...toto.txt">
      <function name="foo" size="0">
         <kind name="arg1" color="red" allowed="yes" value="1..2"/>
         <source name="text" allowed="no" />
      </function>

   </file>
   <file name="C:\\...\\tata.txt">
      <function name="foo" size="25">
         <kind name="arg2" color="red" allowed="yes" value="1..5"/>
         <source name="text" allowed="no" />
      </function>

   </file>
   <file name="C:\\..\\titi.txt">
      <function name="foo" size="60">
         <kind name="arg3" color="green" allowed="no" value="0"/>
         <source name="text" allowed="no" />
      </function>

   </file>
</root>

我需要从titi.txt获取arg3的值吗?

我试过了:

xmlFile = xmlread(myFile);
xmlFile.getElementsByTagName('file')

我怎么能继续?

1 个答案:

答案 0 :(得分:2)

正如函数名称所示,getElementsByTagName返回一个列表 - 在您的情况下将包含所有文件标记。

您可以循环播放该列表,找到titi.txt并获取其属性:

xmlFile = xmlread(myFile);
files = xmlFile.getElementsByTagName('file');
for iF=1:files.getLength()
    f = files.item(iF-1);
    % the filename
    if strcmp(char(f.getAttribute('name')), 'C:\...titi.txt')
        % here you'll have to further recurse into the children
        % of f, e.g. starting with:
        kinds = f.getElementsByTagName('kind');
        % get the first element and its value-attribute
    end
end

当然,更快的替代方法是使用XPath

可能需要花费更多时间才能使其工作,这有点不太容易理解,但它具有为您完成所有循环/过滤逻辑的巨大好处。 这在MATLAB中特别有用,因为这些事情很慢。

factory = javax.xml.xpath.XPathFactory.newInstance();
xpath = factory.newXPath();
% prepare the xpath-query for your use-case:
% get a file under the root element with specified name, the function element beneath
% and finally the value-attribute of the kind-element:
expr = xpath.compile('/root//file[@name=''C:\...titi.txt'']/function/kind/@value');

% evaluate the query - xmlFile is the same as above
% the second argument specifies the return-type - in this case, a simple java-string containing the value of the "value" attribute:
value = expr.evaluate(xmlFile, javax.xml.xpath.XPathConstants.STRING); 
% convert to MATLAB char:
value = char(value);

修改

为了使这成为更通用的解决方案,您可以轻松地以可变方式生成查询字符串:

query = sprintf('/root//file[@name=''%s'']/function/kind/@value', yourFileNameHere);
expr = xpath.comile(query);