关于从头开始构建xml树:从头开始构建xml树-Pugixml C ++

Build an xml tree from scratch - pugixml C++

首先,我想说的是,我一直在使用由Frank Vanden Berghen编写的XML解析器,最近尝试迁移到Pugixml。 我发现过渡有点困难。 希望在这里得到一些帮助。

问题:如何使用pugixml API为下面的小xml从头开始构建树? 我尝试查看pugixml主页上的示例,但大多数示例都使用根节点值进行了硬编码。 我的意思是

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

硬编码。 我也尝试阅读有关xml_document和xml_node文档的信息,但如果我必须从头开始构建树,则无法弄清楚如何开始。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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的大多数示例,但是找不到从头开始创建示例的方法。


请参考手册https://github.com/zeux/pugixml/blob/master/docs/manual.html#manual.modify.add的以下部分以及以下示例代码https://github.com/ zeux / pugixml / blob / master / docs / samples / modify_add.cpp


pugixml主页提供了用于从头开始构建XML树的示例代码。

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

构造xml树