AlliedModders

AlliedModders (https://forums.alliedmods.net/index.php)
-   Scripting (https://forums.alliedmods.net/forumdisplay.php?f=107)
-   -   Merge two KeyValues trees (https://forums.alliedmods.net/showthread.php?t=329507)

OneMore 12-27-2020 08:54

Merge two KeyValues trees
 
Hi guys,

Please advise the easiest way to join two KeyValues trees stored in two separate files with the same root name to one KeyValyes structure.

I mean:

Code:

First kv file file1.txt
"root node"
{
  "key1"
  {
      "subkey1" "subvalue1"
  }
}

Code:

Second kv file file2.txt
"root node"
{
  "key2"
  {
      "subkey2" "subvalue2"
  }
}

I want to have:
Code:

new_kv
"root node"
{
  "key1"
  {
      "subkey1" "subvalue1"
  }
  "key2"
  {
      "subkey2" "subvalue2"
  }
}


Ilusion9 12-27-2020 09:11

Re: Merge two KeyValues trees
 
Try this:

PHP Code:


    KeyValues kv1 
= new KeyValues("root node");
    
KeyValues kv2 = new KeyValues("root node");
    
kv1.ImportFromFile("file1.txt");
    
kv2.ImportFromFile("file2.txt");
    
    
char key[256];
    
char value[256];
    
    if (
kv2.GotoFirstSubKey(false))
    {
        do
        {
            
kv2.GetSectionName(keysizeof(key));
            
kv1.JumpToKey(keytrue);
            
            if (
kv2.GotoFirstSubKey(false))
            {
                do
                {
                    
                    
kv2.GetSectionName(keysizeof(key));
                    
kv2.GetString(NULL_STRINGvaluesizeof(value));
                    
                    
kv1.SetString(keyvalue);
                    
                } while (
kv2.GotoNextKey(false));
                
                
kv.GoBack();
            }
            
            
kv1.Rewind();
            
        } while (
kv2.GotoNextKey(false));
    }

    
delete kv1;
    
delete kv2

Now kv1 is kv1 + kv2 and you can use kv1.ExportToFile.

OneMore 12-27-2020 09:20

Re: Merge two KeyValues trees
 
Thanks!

Is it the easiest way? I mean quite a lot of code :(
I read about a trick with keyname "#base" here: https://forums.alliedmods.net/showthread.php?t=279853
It looks more simple. However, I haven't managed to achieve my result :(

Anyway, thanks a lot for the clean and complete code!

Ilusion9 12-28-2020 06:10

Re: Merge two KeyValues trees
 
https://sm.alliedmods.net/new-api/Ke...ImportFromFile
Imports a file in KeyValues format. The file is read into the current position of the tree.

Try this:
PHP Code:


KeyValues kv 
= new KeyValues("root node");
kv.ImportFromFile("file1.txt");
kv.ImportFromFile("file2.txt");
kv.ExportToFile("merged.txt");
delete kv


OneMore 12-28-2020 10:24

Re: Merge two KeyValues trees
 
Quote:

Originally Posted by Ilusion9 (Post 2730415)
Try this: ...

This is it! Great thanks!


All times are GMT -4. The time now is 22:43.

Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.