I have some data that I read from the registry and wish to modify. Example data looks like this:
<User Blob>
<Item>
<Key>SomeKey</Key>
<Value>false</Value>
</Item>
<Item>
<Key>AnotherKey</Key>
<Value></Value>
</Item>
</User Blob>
<Primary Server Blob>
<Item>
<Key>Just a key</Key>
<Value></Value>
</Item>
<Item>
<Key>And another key</Key>
<Value>true</Value>
</Item>
</Primary Server Blob>
I want to be able to change a certain key’s value. For example:
User Blob.SomeKey = $true
I tried to cast the data to XML or to a HashTable but this gives errors.
Generally, if you have XML data which you wish to modify (not just read), and the data is of a small-enough size (to avoid loading massive objects into memory), you would want to use a Document of some kind. Due to its ability to make use of XPath, I would recommend XmlDocument. (XPath makes this sort of problem simple.)
As you rightly point out though, you will need a single XML root. That’s easy to solve though – just wrap whatever data you have in another root node.
So here’s some code which should do the trick.
I’ve omitted error handling and correct disposal of objects for brevity. I’ll leave that up to you. 🙂
For more info about XmlDocument, see the documentation.
UPDATE
To remove the additional root document again, just use this to get it as a string.
Then save the string using a StreamWriter or File.CreateText or something.