Link 到同一文档中的另一个 XML 节点

Link to another XML node in the same document

XML 文件:

<?xml version="1.0"?>
<Common>
    <Test name="B1">
        <Test id="100"><Name>a test</Name></Test>
        <Test id="101"><Name>another test</Name></Test>
    </Test>
    <Test name="B2">
        <Test id="500"><Name>a simple test</Name></Test>
        <Test id="501"><Name>another simple test</Name></Test>
    </Test>
    <Test name="B6">
        <!-- link to B2 to avoid redundancy -->
    </Test>
</Common>

我想要 link <Test name"B2"> 的内容到 <Test name="B6"> 以避免重新输入相同的数据! (不同的名称是必要的) 引用此 XML 节点需要哪条语句? (pugixml应该可以正确解析)

XML 不支持此类引用。您可以使用自定义 "syntax" 和自定义 C++ 代码解决此问题,例如:

<?xml version="1.0"?>
<Common>
    <Test name="B1">
        <Test id="100"><Name>a test</Name></Test>
        <Test id="101"><Name>another test</Name></Test>
    </Test>
    <Test name="B2">
        <Test id="500"><Name>a simple test</Name></Test>
        <Test id="501"><Name>another simple test</Name></Test>
    </Test>
    <Test name="B6">
        <?link /Common/Test[@name='B2']?>
    </Test>
</Common>

可以用这样的代码加载:

bool resolve_links_rec(pugi::xml_node node)
{
    if (node.type() == pugi::node_pi && strcmp(node.name(), "link") == 0)
    {
        try
        {
            pugi::xml_node parent = node.parent();
            pugi::xpath_node_set ns = parent.select_nodes(node.value());

            for (size_t i = 0; i < ns.size(); ++i)
                parent.insert_copy_before(ns[i].node(), node);

            return true;
        }
        catch (pugi::xpath_exception& e)
        {
            std::cerr << "Error processing link " << node.path() << ": " << e.what() << std::endl;
        }
    }
    else
    {
        for (pugi::xml_node child = node.first_child(); child; )
        {
            pugi::xml_node next = child.next_sibling();

            if (resolve_links_rec(child))
                node.remove_child(child);

            child = next;
        }
    }

    return false;
}