IT Forward
IT Forward

Reputation: 395

How to auto increment xml file version

I have an XML file which I want to increment the version number each time the user clicks btnNewfile.

It must start from 1000 and increment to by 1. I am also confused on which version must increment or both. The problem is the format when I try to debug I get this error:

Input string was not in a correct format.

How can I increment it?

XML:

<resheader name="version">
<value>2.0</value>
</resheader>

What I have tried:

private void btnNewfile_Click(object sender, EventArgs e)
{

    int current = 1000;
    current++;
    var versionNumber = doc.Descendants("value").FirstOrDefault();
    current = (int)versionNumber;
    versionNumber.SetValue(current + 1); //error here;Input string was not in a correct format.
    lbl_Output_Version.Text = versionNumber.ToString();
}

The problem comes here as I have these two:

<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> // i only want to update this one

When I debug it is getting the first one with "text/microsoft-resx" and it throws error after that.

Upvotes: 1

Views: 778

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157048

Use a decimal instead of an int, since your string contains .0. Also you need to get the Value, not the entire element to convert. You can also use Where to select the exact item you want.

XElement versionNumber = doc.Descendants("resheader")
                            .Where(x => x.Attribute("name").Value == "version")
                            .Descendants("value")
                            .First();

decimal current = Convert.ToDecimal(versionNumber.Value, CultureInfo.InvariantCulture);

versionNumber.SetValue(Math.Max(1000, current + 1));

Since you wanted to start at 1000, I added a Math.Max.

Upvotes: 1

Related Questions