Gagan Gupta
Gagan Gupta

Reputation: 1

Adding attribute before other attribute in xdocument

I have below xdocument.

<setup name="NEW">
    <master comment="" gui_namewidth="160" gui_valwidth="40" name="MASTER" type="u8">
        <item comment="" name="Name" value="0"/>
    </master>
    <enum comment="" gui_namewidth="160" gui_valwidth="40" name="Name" type="u8">
        <item comment="" name="1" value="0"/>
    </enum>
</setup>

Now I wanted to add a new attribute crc to setup node and this CRC should be the first attribute in the attribute list I.e. the resultant xdocument should look like this

<setup CRC = "0x1244343" name="NEW">
    <master comment="" gui_namewidth="160" gui_valwidth="40" name="MASTER" type="u8">
        <item comment="" name="Name" value="0"/>
    </master>
    <enum comment="" gui_namewidth="160" gui_valwidth="40" name="Name" type="u8">
        <item comment="" name="1" value="0"/>
    </enum>
</setup>

Adding as first attribute is required for backward compatibility and this will calculate the same CRC of the parent nodes as before.

Upvotes: 0

Views: 56

Answers (1)

jdweng
jdweng

Reputation: 34421

Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<setup name=\"NEW\">" +
                    "<master comment=\"\" gui_namewidth=\"160\" gui_valwidth=\"40\" name=\"MASTER\" type=\"u8\">" +
                        "<item comment=\"\" name=\"Name\" value=\"0\"/>" +
                    "</master>" +
                    "<enum comment=\"\" gui_namewidth=\"160\" gui_valwidth=\"40\" name=\"Name\" type=\"u8\">" +
                        "<item comment=\"\" name=\"1\" value=\"0\"/>" +
                    "</enum>" +
                "</setup>";


            XDocument doc = XDocument.Parse(xml);
            XElement setup = doc.Element("setup");
            setup.ReplaceAttributes(new object[] { new XAttribute("CRC", "0x1244343"), setup.Attributes() });
        }
    }
}

Upvotes: 1

Related Questions