Search code examples
c#unity-game-enginemonodevelopxelement

XElement.SetElementValue overwrites elements


I've the following structure:

<Root name="jack">
     <Ele1>4</Ele1>
     <Ele2>4</Ele2>
     <Ele3>4</Ele3>
     <Ele4>4</Ele4>
</Root>

I want to modify some values so I use the following code:

XElement root1 = new XElement("Root");
root1.SetAttributeValue("name", "jack");
root1.SetElementValue("Ele1", 1);
root1.SetElementValue("Ele2", 2);
root1.SetElementValue("Ele3", 3);

The result of this is a new structure:

<Root name="jack">
     <Ele3>3</Ele3>
</Root>

If I print root1 Debug.Log(root1)after setting the value of Ele2 the result is:

<Root name="jack">
     <Ele2>2</Ele2>
</Root>

Respectively if I do after setting the value of Ele1.

I'm using C# & MonoDevelop for Unity3D.


Solution

  • It seems to be a problem with Unity3D because it's a very simple code. Like I said, the structure is there, so I can read first instead of modify it directly. What I've done after read root1 from the xml file:

    string name;
    foreach ( XElement ele in root1.Elements() ){
        name = ele.Name.LocalName;
        if ( !doNotChange.Contains (name) )
            ele.SetValue ( PlayerPrefs.GetInt( name ) );
    }
            
    

    Where doNotChange is a List of strings that contains those elements who I dont need to modify. I don't really know why SetElementValue does not work in Unity3D but SetValue does. I've reported it to Unity3D. I'll edit the post with their answer.

    EDIT: Unity QA Team answered me

    Hey,

    We have been able to reproduce this bug and have sent it for resolution with our developers.

    We highly appreciate your contribution. If you have further questions, feel free to contact us.