2

我想用 TinyXML 从 xml 文件中解析一些数据。

这是我的 text.xml 文件内容:

<?xml version="1.0" encoding="iso-8859-1"?>
<toto>
  <tutu>
    <tata>
      <user name="toto" pass="13" indice="1"/>
      <user name="tata" pass="142" indice="2"/>
      <user name="titi" pass="azerty" indice="1"/>
    </tata>
  </tutu>
</toto>

我想访问第一个元素“用户”。执行此操作的方法如下:

TiXmlDocument   doc("test.xml");

    if (doc.LoadFile())
    {
        TiXmlNode *elem = doc.FirstChildElement()->FirstChildElement()->FirstChildElement()->FirstChildElement();
std::cout << elem->Value() << std::endl;
}

在输出中:用户。

但是代码非常丑陋而且不通用。我尝试了下面的代码来模拟与上面的代码相同的行为,但它不起作用并且发生了错误。

TiXmlElement *getElementByName(TiXmlDocument &doc, std::string const &elemt_value) 
{
    TiXmlElement *elem = doc.FirstChildElement(); //Tree root

    while (elem)
    {
        if (!std::string(elem->Value()).compare(elemt_value))
            return (elem);
        elem = elem->NextSiblingElement();
    }
    return (NULL);
}

也许我错过了库中可以完成这项工作的一个特殊函数(一个 getElementByName 函数)。我只想获得一个指向值是我正在寻找的元素的指针。有人可以帮助我吗?在此先感谢您的帮助。

4

4 回答 4

4

尝试这个

TiXmlElement * getElementByName(TiXmlDocument & doc, std::string const & elemt_value) {

   TiXmlElement * elem = doc.RootElement(); //Tree root
   while (elem) {
      if (!std::string(elem - > Value()).compare(elemt_value)) return (elem);
      /*elem = elem->NextSiblingElement();*/
      if (elem - > FirstChildElement()) {
         elem = elem - > FirstChildElement();
      } else if (elem - > NextSiblingElement()) {
         elem = elem - > NextSiblingElement();
      } else {
         while (!elem - > Parent() - > NextSiblingElement()) {
            if (elem - > Parent() - > ToElement() == doc.RootElement()) {
               return NULL;
            }
            elem = elem - > Parent() - > NextSiblingElement();
         }
      }
   }
   return (NULL);
}
于 2012-12-16T10:56:12.010 回答
2

当我只是将其复制粘贴到我的代码中时,Adi 的答案不起作用,但我修改了它,现在它对我来说很好。因为我做了很多更改,所以我想我应该在这里发布我的最终代码。

    void parseXML(tinyxml2::XMLDocument& xXmlDocument, std::string sSearchString, std::function<void(tinyxml2::XMLNode*)> fFoundSomeElement)
    {
            if ( xXmlDocument.ErrorID() != tinyxml2::XML_SUCCESS )
            {
                // XML file is not ok ... we throw some exception
                throw DataReceiverException( "XML file parsing failed" );
            } // if

            //ispired by http://stackoverflow.com/questions/11921463/find-a-specific-node-in-a-xml-document-with-tinyxml
            tinyxml2::XMLNode * xElem = xXmlDocument.FirstChild();
            while(xElem)
            {
                if (xElem->Value() && !std::string(xElem->Value()).compare(sSearchString))
                {
                    fFoundSomeElement(xElem);
                }

                /*
                *   We move through the XML tree following these rules (basically in-order tree walk):
                *   
                *   (1) if there is one or more child element(s) visit the first one
                *       else
                *   (2)     if there is one or more next sibling element(s) visit the first one
                *               else
                *   (3)             move to the parent until there is one or more next sibling elements
                *   (4)             if we reach the end break the loop
                */
                if (xElem->FirstChildElement()) //(1)
                    xElem = xElem->FirstChildElement();
                else if (xElem->NextSiblingElement())  //(2)
                    xElem = xElem->NextSiblingElement();
                else
                {
                    while(xElem->Parent() && !xElem->Parent()->NextSiblingElement()) //(3)
                        xElem = xElem->Parent();
                    if(xElem->Parent() && xElem->Parent()->NextSiblingElement())
                        xElem = xElem->Parent()->NextSiblingElement();
                    else //(4)
                        break;
                }//else
            }//while
    }

(为了完整性)示例如何调用该函数:

        tinyxml2::XMLDocument xXmlDocument;

        xXmlDocument.Parse(sXmlDocument.c_str());

        parseXML(xXmlDocument, "user",[](tinyxml2::XMLNode* xElem)
        {
            int iPass;
            xElem->QueryIntAttribute( "pass", &iPass );
            std::cout << iPass << "\n";
        });
于 2015-07-18T05:21:51.940 回答
1
XMLElement *getElementByName(XMLDocument &ele, std::string const &elemt_value)
    {
    XMLElement *elem = ele.FirstChildElement(); //Tree root

    while (elem)
    {
        if (!std::string(elem->Value()).compare(elemt_value))
            return elem;
        if (elem->FirstChildElement())
        {
            elem = elem->FirstChildElement();
        }
        else if (elem->NextSiblingElement())
        {
            elem = elem->NextSiblingElement();
        }
        else
        {
            if (elem->Parent()->ToElement()->NextSiblingElement())
            {
                elem = elem->Parent()->ToElement()->NextSiblingElement();
            }
            else if (elem->Parent()->ToElement()->FirstChildElement()
                        &&  strcmp(elem->Name(), elem->Parent()->ToElement()->FirstChildElement()->Name()))
            {
                elem = elem->Parent()->ToElement()->FirstChildElement();
            }
            else {
                break;
            }
        }
    }
    return NULL;
}

// 对上述解决方案的一个小调整

于 2020-04-01T06:26:11.627 回答
0

您还可以使用结合 lamda-function 的递归函数作为处理程序,逐个遍历您的 XML 元素。

// 
// This function will iterate through your XML tree and call the 'parseElement' function for each found element.
//
void RecursiveXMLParse(TiXmlElement* element, std::function<void(TiXmlElement*)>& parseElement)
{
    if (element != nullptr)
    {
        parseElement(element);
        auto child = element->FirstChildElement();
        if (child != nullptr)
        {
            RecursiveXMLParse(child, parseElement);
        }

        for (auto sibling = element->NextSiblingElement(); sibling != nullptr; sibling = sibling->NextSiblingElement())
        {
            RecursiveXMLParse(sibling, parseElement);
        }
    }
}

用法:只需将 XML 根元素和您的数据处理程序 lambda 函数传递给递归解析器函数。

int main()
{
    //
    // Define your data handler labmda
    //
    std::function<void(TiXmlElement*)>parseElement = [&](TiXmlElement* e) -> void
    {
        if (std::string(elem->Value()).compare("user"))
        {
             // Parse your user data
        }
    };

    // Pass the root element along with the above defined lambda to the recursive function 
    RecursiveXMLParse(doc.RootElement(), parseElement);

    return 0;
}
于 2018-06-06T12:13:51.907 回答