c++tinyxml2

XML GetText from element with attribute


I want to GetText from specific element and attribute from XML using Tinyxml-2, but I cant do it.

My XML like below:

<?xml version="1.0" encoding="UTF-8"?>
<properties>
<entry key="NAME">AAA/entry>
<entry key="SURNAME">BBB</entry>
</properties>

My code is:

  tinyxml2::XMLError eResult = xml_doc.LoadFile("C:\\test.xml");
  if (eResult != tinyxml2::XML_SUCCESS) return false;

  tinyxml2::XMLNode* root = xml_doc.FirstChildElement("properties");
  if (root == NULL) return false;

  tinyxml2::XMLElement* element = root->FirstChildElement("entry");
  if (element == NULL) return false;

  element->GetText()//return first element text "AAA"

How to get others text with same node name and different attribute. Thanks.


Solution

  • You have to read all elements with needed tag. Try like this:

    tinyxml2::XMLElement* element = root->FirstChildElement("entry");
    while (element != nullptr)
    {
        const char * szAttributeText = nullptr;
    
        szAttributeText = element->Attribute("key");
        if (szAttributeText == nullptr) return tinyxml2::XML_ERROR_PARSING_ATTRIBUTE;
        std::string strAttrKey = szAttributeText;
    
        // ...
    
        element = element->NextSiblingElement("entry");
    }