2017-01-30 86 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> 

可以用這樣的代碼加載

相關問題