TinyXML 2数据提取

时间:2016-01-07 10:59:06

标签: xml tinyxml2

我有一个XML文件:

<shape type="obj">
    <string name="filename" value="meshes/cbox_luminaire.obj"/>
    <transform name="toWorld">
        <translate x="0" y="-0.5" z="0"/>
    </transform>

    <ref id="light"/>

    <emitter type="area">
        <spectrum name="radiance" value="400:0, 500:8, 600:15.6, 700:18.4"/>
    </emitter>
</shape>
<shape type="obj">
    <string name="filename" value="meshes/cbox_back.obj"/>

    <ref id="white"/>
</shape>

我需要提取形状的文件路径。

    XMLElement * a = doc.FirstChildElement( "scene" );//->FirstChildElement("shape");

    for(XMLElement* elem = a->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())
    {
        std::string elemName = elem->Value();
        if(elemName=="shape")
            toto.push_back(elem);
    }

  for(unsigned int i =0;i<toto.size();i++)
  {
    const XMLAttribute* tmp = toto[i]->FirstAttribute ();
    std::cout<<tmp->Name()<<":"<<tmp->Value()<<"\n";

  }

我可以检索的唯一数据是第一个属性aka type:obj 如何获取文件名,转换数据(如果存在)和其他数据?

1 个答案:

答案 0 :(得分:0)

效果很好。上面的代码有一些小的更正:

void readShape(XMLNode* n)
{
  if (strcmp(n->ToElement()->FirstAttribute()->Value(), "obj") == 0)
  {
    const char *path = n->FirstChildElement()->FirstAttribute()->Next()->Value();
    std::cout << path << "\n";
    for (XMLNode * current = n->FirstChild();
      current != NULL;
      current = current->NextSibling())
    {
      if (strcmp(current->Value(), "transform") == 0)
        std::cout << "transformation!" << "\n";
    }
  }
}

并在您的主要功能中:

tinyxml2::XMLDocument doc;
doc.LoadFile("Path/To/Xml");


XMLNode * son = doc.FirstChildElement("scene")->FirstChildElement("shape");

for (XMLNode * current = son; current != NULL; current = current->NextSibling())
{ 
  readShape(current); 
}

doc.Clear();