Cyotek.Data.Nbt icon indicating copy to clipboard operation
Cyotek.Data.Nbt copied to clipboard

Method to edit existing values

Open thepwrtank18 opened this issue 4 years ago • 4 comments

Here is my code:

document = NbtDocument.LoadDocument("level.dat");
root = document.DocumentRoot;
root.Name = "Data";
visibleVersion = (TagCompound)root.Value.Add("Version", TagType.Compound); // error here
visibleVersion.Value.Add("Id", (int) 2709);
visibleVersion.Value.Add("Name", (string) "21w15a");
File.Move("level.dat", "level.bak");
document.Save("level.dat");

I've noticed that when trying to run it, it says "Version" already exists, which it does. Is it possible to edit existing values, and if so, how?

thepwrtank18 avatar Apr 17 '21 07:04 thepwrtank18

Fixed it by adding this before adding visibleVersion:

root.Value.Remove("Version");

and this before the addition of values:

visibleVersion.Value.Remove("Id");
visibleVersion.Value.Remove("Name");

However, then it only saves what I edited.

thepwrtank18 avatar Apr 17 '21 07:04 thepwrtank18

Hello,

Apologies for the delay in responding. The Value property of a TagCompound has an indexer for accessing the child items for editing.

If you know the type up-front, you can cast it and set the value of the child

((TagInt)visibleVersion["Id"]).Value = 2709;

If you don't know the type, you can call SetValue, although this boxes primitives such as integers.

visibleVersion["Id"].SetValue(2709);

Regards; Richard Moss

cyotek avatar Apr 26 '21 06:04 cyotek

How would I get visibleVersion to exist without deleting it, then re-creating it?

thepwrtank18 avatar May 07 '21 20:05 thepwrtank18

Nevermind, I think I found it.

root.GetCompound("version")

thepwrtank18 avatar May 07 '21 20:05 thepwrtank18