2

I use tinyxml2 to deal with a string that contains xml. I use the function Parse but it just read a part of the string and return XML_SUCCESS

#include "XML/include/tinyxml2.h"
#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
    std::string xml("<application> <name>something</name> </application>");

    tinyxml2::XMLDocument xmlDoc;
    if (tinyxml2::XML_SUCCESS == xmlDoc.Parse(xml.c_str(), xml.size()))
    {
        tinyxml2::XMLElement* pNode = xmlDoc.FirstChildElement("name");
        std::cout << pNode->GetText() << std::endl;
    }

    return 0;
}

It will throw a exception that tell me the pNode is a nullptr and I checked the _charBuffer of the xmlDoc.

It just contain

<application
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
longack
  • 105
  • 7
  • can you try one more time but without spaces in the xml string – mangusta Aug 30 '19 at 03:17
  • I have tried the "something" version and the result is the same. – longack Aug 30 '19 at 03:19
  • 1
    Does xmlDoc have a `FirstChildElement("application")`? I'm not sure but I think tinyxml has a 'root' element above all the elements in the XML document. – James Picone Aug 30 '19 at 03:48
  • @mangusta whitespace between elements is allowed by the XML spec and parses will ignore it unless told to preserve it – Remy Lebeau Aug 30 '19 at 04:03
  • @RemyLebeau not always. java's dom parser treats spaces as separate elements. unrelated to this question though – mangusta Aug 30 '19 at 04:24
  • @mangusta that behavior can be controlled with [`XMLParser.setPreserveWhitespace()`](https://docs.oracle.com/cd/B14099_19/web.1012/b12024/oracle/xml/parser/v2/XMLParser.html#setPreserveWhitespace(boolean)) – Remy Lebeau Aug 30 '19 at 05:34
  • @RemyLebeau I mean that some parsers default to reading whitespaces as elements while others default to ignoring them. java's dom parser allows controlling, probably there exists a parser out there which does not – mangusta Aug 30 '19 at 05:43

1 Answers1

2

I find the question is that xmlDoc do not contain "name". It's the "application" contains the "name"

tinyxml2::XMLElement* pRoot = xmlDoc.RootElement();
tinyxml2::XMLElement* pNode = pRoot->FirstChildElement("name");
longack
  • 105
  • 7