【问题标题】:Getting duplicate node values when parsing XML file using RapidXML使用 RapidXML 解析 XML 文件时获取重复的节点值
【发布时间】:2015-12-04 11:46:54
【问题描述】:

我需要使用 RapidXML 读取一个简单的 XML 文件。我已将 XML 文件加载到字符串变量中并将其传递给解析器。我需要获取所有节点名称和值(如果存在)。 我的问题是以下值最终会重复:

  • stepID->值
  • stepHeading1->值
  • stepText->值

这是描述问题的图片:

如果 stepID、stepHeading1 和 stepText 节点没有任何子节点,为什么我的代码会给我所有这些重复值?另外,当节点值变成那样时,为什么代码不给我重复的节点名称?

------------下面的XML文件------------

<?xml version="1.0" encoding="UTF-8"?>
<game>
    <step>
        <stepID>Name</stepID>
        <stepHeading1>Title1</stepHeading1>
        <stepHeading2></stepHeading2>
        <stepHeading3></stepHeading3>
        <stepHeading4></stepHeading4>
        <stepHeading5></stepHeading5>
        <stepHeading6></stepHeading6>
        <stepText>First Step First Step First Step </stepText>
        <link>
            <linkStepID>First Link Name</linkStepID>
            <linkText>First Link Text</linkText>
        </link>
    </step>
</game>

------------ 下面的代码------------

xml_document<>doc;
doc.parse<0>(&( dataForParser1.getLoadedXMLfile() )[0]);

xml_node<> *rootNode = doc.first_node();
xml_node <> *pStep = 0;
xml_node <> *pDiff = 0;
xml_node <> *pLink = 0;

for (xml_node <> *pStep = rootNode->first_node("step"); pStep; pStep = pStep->next_sibling())
{
    cout << pStep->name() << "   " << pStep->value() << endl;

    for (xml_node <> *pDiff = pStep->first_node(); pDiff; pDiff = pDiff->next_sibling())
    {
        cout << pDiff->name() << "   " << pDiff->value() << endl;

        for (xml_node <> *pLink = pDiff->first_node(); pLink; pLink = pLink->next_sibling())
        {
            cout << pLink->name() << "   " << pLink->value() << endl;
        }
    }
    cout << endl << endl;
}

【问题讨论】:

    标签: c++ xml rapidxml


    【解决方案1】:

    您遇到的问题是由于您将标志应用于parse 方法:

    doc.parse<0>(&( dataForParser1.getLoadedXMLfile() )[0]);
    

    这里使用0时,节点数据会被转换成一个单独的子节点。

    尝试改用parse&lt;1&gt;,数据应保留在父节点中。

    此信息可以在rapidxml.hpp 文件中找到,以及其他标志:

    //! Parse flag instructing the parser to not create data nodes. 
    //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified.
    //! Can be combined with other flags by use of | operator.
    //! <br><br>
    //! See xml_document::parse() function.
    const int parse_no_data_nodes = 0x1;          
    

    【讨论】:

    • 有效!感谢 Mir178249 的帮助和编辑我的帖子:)
    • @wojtek:太好了。乐于助人!
    猜你喜欢
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2021-09-07
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多