让我说我有一个看起来像这样的XML文件
<NOTE>
<TO>
<CONTACT>
<NAME>Tove</NAME>
<EMAIL>tove@home.com</EMAIL>
</CONTACT>
<CONTACT>
<NAME>Biggles</NAME>
<EMAIL>biggles@home.com</EMAIL>
</CONTACT>
</TO>
<FROM>
<CONTACT>
<NAME>Jani</NAME>
<EMAIL>jani@home.com</EMAIL>
</CONTACT>
</FROM>
<HEADING>Reminder</HEADING>
<BODY>Party this weekend!</BODY>
</NOTE>
使用NativeXML(至少到版本3.06)和此代码
procedure TForm1.btnLoad1st2ndClick(Sender: TObject);
// Load an XML document and show the nodes present by enumerating them. Here
// we do only levels 1 and 2. An iterative approach could show all levels deep
var
i, j: integer;
NodeLevel1, NodeLevel2: TXmlNode;
begin
// Clear the memo and create instance
Memo1.Lines.Clear;
FXml.Clear;
// Load the XML file
FXml.LoadFromFile(edXmlFileOpen.Text);
// The Root property contains the root node, we use it as a base
if assigned(FXml.Root) then
begin
// Iterate through all the child nodes of Root (level 1)
for i := 0 to FXml.Root.NodeCount - 1 do
begin
NodeLevel1 := FXml.Root.Nodes[i];
// Add the name of each child to the memo
Memo1.Lines.Add(string(NodeLevel1.Name));
// Also iterate through the grandchilds (level 2)
for j := 0 to NodeLevel1.NodeCount - 1 do
begin
NodeLevel2 := NodeLevel1.Nodes[j];
// Add these names too, with an indent
Memo1.Lines.Add(' ' + string(NodeLevel2.Name));
end;
end;
end;
end;
我得到了这个回复
TO
CONTACT
CONTACT
FROM
CONTACT
HEADING
BODY
这是我的预期
但现在我在版本4.07中使用NativeXML,并且使用相同的代码,结果是
WhiteSpace
TO
WhiteSpace
CONTACT
WhiteSpace
CONTACT
WhiteSpace
WhiteSpace
FROM
WhiteSpace
CONTACT
WhiteSpace
WhiteSpace
HEADING
CharData
WhiteSpace
BODY
CharData
WhiteSpace
你猜在现实生活中,XML会更复杂一些。有没有办法尽可能简单地获得与之前版本的NativeXML相同的结果?
感谢您的帮助
PS:顺便说一下,我看看这篇文章 “How do I iterate through similar nodes in an XML document using NativeXML in Delphi?” 但第一个提出的解决方案,与我的样本类似,不起作用。第二个意味着使用节点列表,我想避免的。答案 0 :(得分:1)
您应该只使用xml.root.ElementCount
和xml.root.Elements[i]
属性而不是NodeCount
&amp; Nodes[]
(与nodelevel1.
相同)以实现所需的输出