c++ - 为什么 libxml2 在元素名称上输出 "text"(当它不是 "text"时)?

标签 c++ libxml2

我使用 libxml2 进行 XML 解析。 libxml 网站上的示例代码很难理解,而且似乎缺少一些细节。我通过谷歌搜索得到了以下代码,所以我什至认为这不是正确的方法,但它在我编写的示例学习程序中有效,但不是这个。我仍然不知道在 C++ 中使用 libxml 的正确方法,所以我在黑暗中奔跑,希望能找到有用的东西。

XML 文件正确加载,当此函数正确输出 root->name 时,但是当它通过子节点时,它仅在 cur 处输出 text ->name 我不知道为什么。我必须将计数器放在那里以阻止它进入无限循环。我在 XML 文件的某处读到空白可能会导致此问题,但我不知道该怎么做。我只想要部件名称和 ID。

xmlNode *cur = root;
cur = cur->xmlChildrenNode;

ofstream out;
out.open("errorlog.txt", ios::app);
out << "attempting reading current node\n";
out << "root: " << root->name << endl;

int counter = 0;

// advance until it hits stars
while(cur != NULL && counter < 10){
if ((!xmlStrcmp(cur->name, (const xmlChar *)"parts")))
    break;

    cur->next;
    counter++;
}

out << "counter: " << counter << endl;
out << "child: " << cur->name << endl;

这是我正在使用的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<netlist>
    <parts>
        <part name="part10">
            <attribute name="id">1</attribute>
        </part>
        <part name="part20">
            <attribute name="id">2</attribute>
        </part>
        <part name="part30">
            <attribute name="id">3</attribute>
        </part>
    </parts>

    <junk>
        <stuff id="3" />
        <stuff id="4" />
        <stuff id="5" />
    </junk>
</netlist>

最佳答案

对于libxml2来说,每个节点的下一个子节点系统默认是一个空白文档,在使用DOM树解析XML文档时,由于默认的方式是将节点之间的空格作为第一个子节点,您可以调用函数 xmlKeepBlanksDefault(0) 来忽略空格。

关于c++ - 为什么 libxml2 在元素名称上输出 "text"(当它不是 "text"时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3472099/

相关文章:

c++ - 如何在 Apache Ignite C++ 中从缓存中获取所有 key

c++ - CMake + CUDA + OpenCV

ubuntu - 尝试在 ubuntu 上安装 libxml2-dev 时出现错误消息

c - xpath 表达式中缺失属性的默认值

c++ - cpp 在 std::list 的该位置之后移动一些元素

带有 boost scoped_ptr 的 C++ 多态性

c++ - 渲染时 3D 立方体出现拉伸(stretch)

c++ - 如何随时停止使用 LIBXML SAX 解析 xml 文档?

c - 从 xmlNode 获取源文件名?

php - 从 PHP 执行 shell 命令