从头构建XML树 - pugixml C++

10
首先,我想说我一直在使用Frank Vanden Berghen编写的XML解析器,最近尝试迁移到Pugixml。我发现这个转换有些困难。希望在这里得到一些帮助。
问题:如何使用Pugixml API从头构建一个树来解析下面的小型XML?我尝试查看Pugixml主页上的示例,但它们大多数都是硬编码的根节点值。我的意思是:
if (!doc.load("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;

这段代码中有硬编码。我尝试阅读xml_document和xml_node文档,但是无法弄清楚如何从头开始构建树形结构。

#include "pugixml.hpp"

#include <string.h>
#include <iostream>

int main()
{
    pugi::xml_document doc;
    if (!doc.load("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;

    //[code_modify_base_node
    pugi::xml_node node = doc.child("node");

    // change node name
    std::cout << node.set_name("notnode");
    std::cout << ", new node name: " << node.name() << std::endl;

    // change comment text
    std::cout << doc.last_child().set_value("useless comment");
    std::cout << ", new comment text: " << doc.last_child().value() << std::endl;

    // we can't change value of the element or name of the comment
    std::cout << node.set_value("1") << ", " << doc.last_child().set_name("2") << std::endl;
    //]

    //[code_modify_base_attr
    pugi::xml_attribute attr = node.attribute("id");

    // change attribute name/value
    std::cout << attr.set_name("key") << ", " << attr.set_value("345");
    std::cout << ", new attribute: " << attr.name() << "=" << attr.value() << std::endl;

    // we can use numbers or booleans
    attr.set_value(1.234);
    std::cout << "new attribute value: " << attr.value() << std::endl;

    // we can also use assignment operators for more concise code
    attr = true;
    std::cout << "final attribute value: " << attr.value() << std::endl;
    //]
}

// vim:et

XML:

<?xml version="1.0" encoding="UTF-8"?>
<d:testrequest xmlns:d="DAV:" xmlns:o="urn:example.com:testdrive">
   <d:basicsearch>
      <d:select>
         <d:prop>
            <o:versionnumber/>
            <d:creationdate />
         </d:prop>
      </d:select>
      <d:from>
         <d:scope>
            <d:href>/</d:href>
            <d:depth>infinity</d:depth>
         </d:scope>
      </d:from>
      <d:where>
         <d:like>
            <d:prop>
               <o:name />
            </d:prop>
            <d:literal>%img%</d:literal>
         </d:like>
      </d:where>
    </d:basicsearch>
</d:testrequest>

我看到了很多关于如何读取/解析xml的例子,但我找不到如何从头开始创建xml的方法。

2个回答


10

pugixml的首页提供了从头构建XML树的示例代码。

摘要:使用pugi::xml_document doc的默认构造函数,然后使用append_child添加根节点。通常,先插入一个节点。插入调用的返回值然后作为句柄填充XML节点。

构建XML树


1
为了以后参考:示例已移至Github。 简而言之:对于doc,使用默认构造函数,然后使用append_child添加根节点。通常,首先插入一个节点。插入调用的返回值然后作为填充XML节点的句柄。 - starturtle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接