TinyXML2 查询文本(如果属性匹配)

TinyXML2 query text if attribute matches

本文关键字:属性 如果 查询 文本 TinyXML2      更新时间:2023-10-16

我正在尝试找出一种方法,从我使用TinyXML2创建的XML文档中加载文本。这是整个文档。

<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" width="15" height="13" tilewidth="32" tileheight="32">
 <tileset firstgid="1" name="Background" tilewidth="32" tileheight="32">
  <image source="background.png" width="64" height="32"/>
 </tileset>
 <tileset firstgid="3" name="Block" tilewidth="32" tileheight="32">
  <image source="block.png" width="32" height="32"/>
 </tileset>
 <layer name="Background" width="15" height="13">
  <data encoding="base64">
   AgAAAAIAAAACAAAA...
  </data>
 </layer>
 <layer name="Block" width="15" height="13">
  <data encoding="base64">
   AwAAAAMAAAADAAAAAwAAAAM...
  </data>
 </layer>
</map>

基本上,仅当图层名称为 "Background" 时,我才想将文本从 <data> 复制到名为 background 的字符串中。

我得到了其他变量,如下所示:

// Get the basic information about the level
version = doc.FirstChildElement("map")->FloatAttribute("version");
orientation = doc.FirstChildElement("map")->Attribute("orientation");
mapWidth = doc.FirstChildElement("map")->IntAttribute("width");
mapHeight = doc.FirstChildElement("map")->IntAttribute("height");

这很好用,因为我知道元素名称和属性名称。有没有办法说得到doc.FirstChildElement("map")->FirstChildElement("layer"),如果== "Background",得到文本。

我将如何实现这一点?

我知道这个线程很旧,但以防万一有人仔细阅读互联网可能会像我一样偶然发现这个问题,我想指出 Xanx 的答案可以稍微简化一下。

tinyxml2.h中,它说对于函数const char* Attribute( const char* name, const char* value=0 ) const,如果value参数不为空,则函数仅在valuename匹配时才返回。根据文件中的注释,这:

if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();

可以这样写:

if ( ele->Attribute( "foo" ) ) {
    if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar();
}

所以 Xanx 提供的代码可以这样重写:

XMLElement * node =  doc.FirstChildElement("map")->FirstChildElement("layer");
std::string value;
if (node->Attribute("name", "Background")) // no need for strcmp()
{
   value = node->FirtChildElement("data")->GetText();
}

一个小小的变化,是的,但我想补充一些东西。

我建议你做这样的事情:

XMLElement * node =  doc.FirstChildElement("map")->FirstChildElement("layer");
std::string value;
// Get the Data element's text, if its a background:
if (strcmp(node->Attribute("name"), "Background") == 0)
{
   value = node->FirtChildElement("data")->GetText();
}
auto bgData = text (find_element (doc, "map/layer[@name='Background']/data"));

使用 tinyxml2 扩展名 ( #include <tixml2ex.h> )。注意:真的应该被包裹在一个尝试/捕获块中。正在进行的工作和文档不完整(可以从测试示例中推断出来,直到准备就绪)。

我会顺便提一下,其他两个答案只有在首先出现所需的<layer>元素时才能正常工作。

相关文章: