在TinyXML2中,如何使用XMLText来获取带内联标记的整个Text

时间:2015-01-02 23:21:09

标签: c++ tinyxml2

代码来自http://www.grinninglizard.com/tinyxml2docs/_example-3.html

 static const char* xml =
        "<?xml version=\"1.0\"?>"
        "<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
        "<PLAY>"
        "<TITLE>A Midsummer <b>Night's Dream</b></TITLE>"
        "</PLAY>";
XMLDocument doc;
doc.Parse(xml);
XMLElement* titleElement = doc.FirstChildElement("PLAY")->FirstChildElement("TITLE");
XMLText* textNode = titleElement->FirstChild()->ToText();
auto title = textNode->Value();

标题应包含A Midsummer <b>Night's Dream</b>作为介绍说明。但代码的结果仍为A Midsummer。任何人都可以告诉我我的代码有什么问题,或者其他一些功能来实现解析。

2 个答案:

答案 0 :(得分:1)

这是一个简短但完整的程序,它可以获取字符串的两个部分以及找到第二部分的元素:

#include <stdio.h>
#include <stdlib.h>

#include "../tinyxml2.h"
using namespace tinyxml2;

int main(int argc, char *argv[])
{
    static const char* xml =
        "<?xml version=\"1.0\"?>"
        "<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
        "<PLAY>"
        "<TITLE>A Midsummer Night's <b>Dream</b></TITLE>"
        "</PLAY>";

    XMLDocument doc;            /* DOM tree */

    doc.Parse(xml);         /* Parse the XML */

    XMLElement* titleElement =
    doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" );

    const char* title = titleElement->GetText();    /* cheap approach */
    printf( "Name of play (part 1): %s\n", title );

    XMLNode *tp = titleElement->FirstChild();
    printf("part 1 = %s\n", tp->Value());   /* A Midsummer Night's */

    tp = tp->NextSibling();         /* point to the <b> element */
    printf("element for part 2 = %s\n", tp->Value());   /* b */
    tp = tp->FirstChild();          /* point to b's text node */
    printf("part 2 = %s\n", tp->Value());   /* Dream */
}

输出结果为:

Name of play (part 1): A Midsummer Night's 
part 1 = A Midsummer Night's 
element for part 2 = b
part 2 = Dream

正如之前的回答中所提到的,使用XML提供的文本不会显示为单个字符串。要获得所有组件,需要遍历更多的树。

答案 1 :(得分:0)

Night's Dream不在元素<TITLE>中,而在<b>内的元素<TITLE>中。

如果您想在元素的文本中包含<b>Night's Dream</b>,则应该将其转义(请参阅http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references):

static const char* xml =
        "<?xml version=\"1.0\"?>"
        "<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
        "<PLAY>"
        "<TITLE>A Midsummer &lt;b&gt;Night's Dream&lt;/b&gt;</TITLE>"
        "</PLAY>";