1

对于具有相同子节点名称的节点的所有子节点,我得到相同的节点值。例如,在我的代码中,在所有情况下,我都将节点名称的节点数据值作为 ACHRA。我想获得正确的节点值。请指导。

这是我的代码:

XML 代码:

<?xml version='1.0' encoding = 'UTF-8' ?>

<student>
  <person>
    <name name="AttractMode0" >Achra</name>
    <name name="abc" >Elivia</name>
    <name name="def" >Christina</name>
    <gender name="AttractMode1" >female</gender>
    <country name="AttractMode2" >India</country>
  </person> 

  <person>
    <name name="AttractMode3" >georg</name>
    <gender name="AttractMode4" >male</gender>
    <country name="AttractMode5" >Austria</country>  
  </person>
</student>

C++ 代码

#include "pugixml-1.4/src/pugixml.cpp" 
#include <iostream> 
#include <sstream> 
int main()
{
    pugi::xml_document doc;
    std::string namePerson;

    if (!doc.load_file("student.xml")) return -1;

    pugi::xml_node persons = doc.child("student");
    std::cout << persons.name() << std::endl;

for (pugi::xml_node person = persons.first_child(); person; person = person.next_sibling())
    {

        for (pugi::xml_attribute attr = person.first_attribute(); attr; attr = attr.next_attribute())
        {
            std::cout << " " << attr.name() << "=" << attr.value() << std::endl;
        }

        for (pugi::xml_node child = person.first_child(); child; child = child.next_sibling())
        {
            std::cout << child.name() <<"="<< person.child_value(child.name())<<std::endl;     // get element name
            // iterate through all attributes
            for (pugi::xml_attribute attr = child.first_attribute(); attr; attr = attr.next_attribute())
            {
                std::cout << " " << attr.name() << "=" << attr.value() << std::endl;
            }
            std::cout << std::endl;
        }
    }
    std::cout << std::endl;
}

我的输出是:

student

Person: 
name=Achra
 name=AttractMode0

name=Achra
 name=abc

name=Achra
 name=def

gender=female
 name=AttractMode1

country=India
 name=AttractMode2


Person: 
name=georg
 name=AttractMode3

gender=male
 name=AttractMode4

country=Austria
 name=AttractMode5
4

1 回答 1

1

引用您的pugixml图书馆文档:

纯字符数据节点 (node_pcdata) 表示 XML 中的纯文本。PCDATA 节点有一个值,但没有名称或子/属性。请注意,纯字符数据不是元素节点的一部分,而是有自己的节点;例如,一个元素节点可以有多个子 PCDATA 节点。

只需替换这一行:

std::cout << child.name() << "=" << person.child_value(child.name()) << std::endl;

像这样:

pugi::xml_node pcdata = child.first_child();
std::cout << child.name() << " = " << pcdata.value() << std::endl;

现在的输出是:

name = Achra
 name = AttractMode0
name = Elivia
 name = abc
name = Christina
 name = def
gender = female
 name = AttractMode1
country = India
 name = AttractMode2
name = georg
 name = AttractMode3
gender = male
 name = AttractMode4
country = Austria
 name = AttractMode5

您可能还想看看这个步行者- 它似乎更简单。

于 2014-08-08T12:14:52.723 回答