2017-01-30 59 views
0

XML文件中:链接到另一个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> 

我想链接的<Test name"B2"><Test name="B6">内容,以避免重复输入相同的数据! (需要不同的名称)需要哪个语句来引用此XML节点? (pugixml应该能够正确解析它)

回答

1

XML不支持此类引用。你可以用自定义的“语法”和自定义的C++代码解决这个问题,例如:

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; 
} 

<?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> 

可以用这样的代码加载

相关问题