问题
I would like to search a text in xml file and check that it has the correct value using Matlab.
I tried :
myFolder = 'folder1';
OutputFile = fullfile(myFolder ,'info.xml');
xmlNode = xmlread(OutputFile );
I would like to check that 'characteristic','color' options exists and that they have respectively the values : hybrid and red ?
info.xml content--------------
<?xml version="1.0" encoding="utf-8"?>
<Custom_project name="" val="True" name="file1" path="file:/C:/Users/Local/Temp/info.xml" version="1.0">
<verif="true" name="values" path="file:/C:/Users/Temp/folder1">
<optList name="values">
<opt name="color">red</option>
<opt name="police">calibri</option>
<opt name="font">blue</option>
</optList>
</verif>
<toto="myvalue" name="option1">
<opt name="myvalue_1">32</option>
<opt name="-total">All</option>
<opt name="characteristic">hybrid</option>
</toto>
回答1:
If using xmlread
is not required, this is one possible solution. Multiple definitions of the same XML options are not checked, so any matching option name - option value pair is counted as a match.
% function that uses regexp
to find matching string in XMLdata.
function [IsMatch] = xmlmatch(XMLdata, Variable, Value)
IsMatch = ~isempty(regexp(XMLdata, [ '.*<opt\s*name="', Variable, '">', Value, '</option>.*' ]));
return
% open the file, get file ID
fid = fopen('info.xml');
% read the file contents (assume text file).
XMLdata = fscanf(fid, '%s');
% check the XMLdata's variables' values:
IsColorRed = xmlmatch(XMLdata, 'color', 'red');
IsColorRed =
1
IsColorBlue = xmlmatch(XMLdata, 'color', 'blue');
IsColorBlue =
0
IsCharacteristicHybrid = xmlmatch(XMLdata, 'characteristic', 'hybrid');
IsCharacteristicHybrid =
1
IsCharacteristicHybr = xmlmatch(XMLdata, 'characteristic', 'hybr');
IsCharacteristicHybr =
0
% close the file.
fclose(fid);
来源:https://stackoverflow.com/questions/10177241/search-a-text-using-xmlread-in-xml-file