2009年下半年全国计算机等级考试你准备好了没?考计算机等级考试的朋友,2009年下半年全国计算机等级考试时间是2009年9月19日至23日。更多优质资料尽在
考试大论坛 考试大在线题库 XML 文档的节点是标准的树形结构,可以通过递归或者回溯算法来遍历所有的节点。
本例使用递归算法为例,制作了2个遍历 XML 文档的例子。
第一个例子,给出一个 XML 节点,遍历所有子节点-不包括起始节点。
第二个例子,给出一个 XML 节点,遍历所给的节点及其下属的所有子节点。
以上2个示例均列举出了 XML 文档的标签属性和文本值,是比较完整的示例代码。
<?xml version=/"1.0/" encoding=/"gb2312/"?>
<root website=/"http://www.why100000.com/">
<channel id=/"1/" tagname=/"channel/">
<topic id=/"1-1/" tagname=/"topic/">Windows频道</topic>
<Url id=/"1-2/" tagname=/"Url/">www.why100000.com/_windows</Url>
</channel>
<channel id=/"2/" tagname=/"channel/">
<topic id=/"2-1/" tagname=/"topic/">代码实验室</topic>
<subWeb id=/"2-2/" tagname=/"subWeb/">http://lab.why100000.com</subWeb>
</channel>
<BBS id=/"03/" tagname=/"BBS/">
<topic id=/"03-1/" tagname=/"topic/">电脑学习社区</topic>
<subWeb id=/"03-2/" tagname=/"subWeb/">http://bbs.why100000.com</subWeb>
<subBBS id=/"03-3/">
<subBBStopic id=/"03-3-1/">菜鸟学院</subBBStopic>
<subBBStopic id=/"03-3-2/">问吧</subBBStopic>
<subBBStopic id=/"03-3-3/">学吧</subBBStopic>
<subBBStopic id=/"03-3-4/">回吧</subBBStopic>
<subBBStopic id=/"03-3-5/"></subBBStopic>
<subBBStopic></subBBStopic>
</subBBS>
</BBS>
<AnatherTag note=/"testTag-1/"/>
<AnatherTag/>
</root>
{----------------------------------------------------------------------}
function TForm1.GetXmlTree1(nNode: IXMLNode): string;
var
i, j: integer;
begin
for i:=0 to nNode.ChildNodes.Count-1 do
begin
s := s + ’<’ + nNode.ChildNodes.Nodes[i].NodeName;
for j:=0 to nNode.ChildNodes[i].AttributeNodes.Count-1 do
begin
s := s + ’ ’+ nNode.ChildNodes[i].AttributeNodes[j].NodeName;
s := s + ’=/"’+ nNode.ChildNodes[i].AttributeNodes[j].NodeValue +’/"’;
end;
s := s + ’>’;
if nNode.ChildNodes.Nodes[i].IsTextElement then
s := s + nNode.ChildNodes.Nodes[i].Text;
if nNode.HasChildNodes and not nNode.ChildNodes.Nodes[i].IsTextElement then
begin
s := s + #13 + #10;
GetXmlTree1(nNode.ChildNodes.Nodes[i]);
end;
s := s + ’</’+ nNode.ChildNodes.Nodes[i].NodeName +’>’ + #13 + #10;
end;
result := s;
end;