我想从XML文件中提取信息。我尝试了Mathworks中的示例,但它没有用。以下是文件中的示例信息:
<?xml version="1.0" encoding="iso-8859-1"?>
<CS-info>
<cs name="abc">
<var name="a" unit="s1"/>
<var name="b" unit="s2"/>
.
.
</cs>
.
.
.
</CS-info>
当选择“cs name”时,该节点中相应的变量名称和单位应该被提取为单元格数组。有人有解决方案吗? 预期的输出是
output={'a','s1';'b','s2';...};
答案 0 :(得分:1)
在xmlread
的文档中,已经显示了几个示例函数来帮助您解析XML文档。如果代码被删除,代码将被复制如下 -
function theStruct = parseXML(filename)
% PARSEXML Convert XML file to a MATLAB structure.
try
tree = xmlread(filename);
catch
error('Failed to read XML file %s.',filename);
end
% Recurse over child nodes. This could run into problems
% with very deeply nested trees.
try
theStruct = parseChildNodes(tree);
catch
error('Unable to parse XML file %s.',filename);
end
% ----- Local function PARSECHILDNODES -----
function children = parseChildNodes(theNode)
% Recurse over node children.
children = [];
if theNode.hasChildNodes
childNodes = theNode.getChildNodes;
numChildNodes = childNodes.getLength;
allocCell = cell(1, numChildNodes);
children = struct( ...
'Name', allocCell, 'Attributes', allocCell, ...
'Data', allocCell, 'Children', allocCell);
for count = 1:numChildNodes
theChild = childNodes.item(count-1);
children(count) = makeStructFromNode(theChild);
end
end
% ----- Local function MAKESTRUCTFROMNODE -----
function nodeStruct = makeStructFromNode(theNode)
% Create structure of node info.
nodeStruct = struct( ...
'Name', char(theNode.getNodeName), ...
'Attributes', parseAttributes(theNode), ...
'Data', '', ...
'Children', parseChildNodes(theNode));
if any(strcmp(methods(theNode), 'getData'))
nodeStruct.Data = char(theNode.getData);
else
nodeStruct.Data = '';
end
% ----- Local function PARSEATTRIBUTES -----
function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = [];
if theNode.hasAttributes
theAttributes = theNode.getAttributes;
numAttributes = theAttributes.getLength;
allocCell = cell(1, numAttributes);
attributes = struct('Name', allocCell, 'Value', ...
allocCell);
for count = 1:numAttributes
attrib = theAttributes.item(count-1);
attributes(count).Name = char(attrib.getName);
attributes(count).Value = char(attrib.getValue);
end
end
它易于使用,
str = 'http://stackoverflow.com/feeds/question/25047975';
x = parseXML(str);
要查找所有<cs>
个节点,您可以执行树遍历,并选择名称为name
的所有节点的属性unit
和cs
。