Search Unity

How to Append the data in the middle in xml

Discussion in 'Scripting' started by Alexander21, Nov 18, 2020.

  1. Alexander21

    Alexander21

    Joined:
    Dec 14, 2015
    Posts:
    302
    Hi All

    In my project I have an xml .

    Code (CSharp):
    1. Ranks>
    2.   <Rank number="1">
    3.     <Mark>3</Mark>
    4.     <Feedback>Good </Feedback>
    5.   </Rank>
    6. <Rank number="2">
    7.     <Mark>3</Mark>
    8.     <Feedback>Good </Feedback>
    9.   </Rank>
    10. <Rank number="3">
    11.     <Mark>3</Mark>
    12.     <Feedback>Good </Feedback>
    13.   </Rank>
    14. <Rank number="4">
    15.     <Mark>3</Mark>
    16.     <Feedback>Good </Feedback>
    17.   </Rank>
    18.   </Ranks>
    it will go infinite...

    I have to Insert the Rank 10(mark,feedback) after the Rank 2. How can i do it.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Unless you want to do crazy text search / replace (not advisable), use an XML processing package to do this. I believe there are some on the asset store, such as JSON .NET, but I don't use XML so I'm not sure of its depth of features.

    In general, never use XML ever ever ever, since it is 2020 and we have way better ways of representing serialized data. One better way is JSON, and that is going to be far easier to reason about than XML.
     
    Bunny83 likes this.
  3. diego-giacomelli

    diego-giacomelli

    Joined:
    Oct 27, 2012
    Posts:
    26
    You can use the classes from System.Xml namespace to read your XML file and then use the XmlNode.InsertAfter method to insert the Rank 10 on the desired position.

    However, I agree with @Kurt-Dekker, better to use JSON to represent serialized data.
     
    Kurt-Dekker and Bunny83 like this.