当 TinyXML 访问者函数返回 false 时,为什么它停止解析同级?
我们采用 Tiny XML 作为我们的 XML 解析器。我正在编写代码从 XML 文件中获取调色板,并编写了一个如下的访问者函数:
PALETTE_PARSER::VisitEnter( const TiXmlElement& Element, const TiXmlAttribute* First Attribute)
{
if( Element.ValueStr() == "palette" )
{
AddPalette( Element );
return( true );
}
else
{
return( false );
}
}
我惊讶地发现它解析了第一个 palette
元素,然后停止了。当我检查时,文档说
如果从 Visit 方法返回“true”,递归解析将继续。如果你回来 false,不会访问此节点或其兄弟节点的子节点。
对我来说,不解析孩子们是有道理的,但兄弟姐妹对我来说似乎很奇怪。这种行为的原因是什么?有什么办法让它做我想做的事吗?
也就是说,我只对调色板元素感兴趣,但可能不止一个(以及其他元素)。我想返回 false 以跳过其他元素类型,而不是必须递归处理它们,同时仍然找到所有调色板。所以我想我正在寻找一种仅访问调色板元素的方法,而完全忽略其他所有内容。
We have adopted Tiny XML as our XML parser. I am writing code to grab palettes out of an XML file, and wrote a visitor function like this:
PALETTE_PARSER::VisitEnter( const TiXmlElement& Element, const TiXmlAttribute* First Attribute)
{
if( Element.ValueStr() == "palette" )
{
AddPalette( Element );
return( true );
}
else
{
return( false );
}
}
I found to my surprise that this parsed the first palette
element, and then stopped. When I checked, the documentation said
If you return 'true' from a Visit method, recursive parsing will continue. If you return
false, no children of this node or its sibilings will be Visited.
It makes sense to me not to parse the children, but the siblings seems weird to me. What is the reason for this behavior? Is there any way to get it to do what I want?
That is, I am interested only in the palette elements, but there may be more than one of them (as well as other elements). I wanted to return false to skip the other element types rather than having to process them recursively, while still finding all the palettes. So I guess I am looking for a way to visit only the palette elements, while completely ignoring everything else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目的是允许您递归地搜索节点树,并在找到您要查找的内容后立即停止。
进一步的讨论意味着所有
元素都是树中某个特定节点的子元素。Visit
用于检查整个(子)树,假设您感兴趣的节点(在本例中为
元素)可能位于任何深度。如果情况并非如此,那么它就不是完成这项工作的工具。
您可以使用
FirstChild
/LastChild
/IterateChildren
/等。成员函数迭代包含所有
元素的节点的子节点,并对实际存在的节点(经检查)执行任何您需要执行的操作< ;palette>
元素,并忽略其他元素。The purpose is to allow you to search a tree of nodes recursively, and stop as soon as you have found whatever it is you are looking for.
Further discussion implies that all the
<palette>
elements are children of some specific node in the tree.Visit
is for examining the entire (sub)tree, under the assumption that the nodes you're interested in (<palette>
elements in this case) might be found at any depth.If that's not the case, then it's not the tool for the job.
You can use
FirstChild
/LastChild
/IterateChildren
/etc. member functions to iterate over the children of whichever node it is that contains all the<palette>
elements, and do whatever you need to do with the nodes that actually are (upon inspection)<palette>
elements, and ignore the others.