1

I have tried several methods, none of which appear to work...

You can see the different methods I have tried by taking a look at the commented lines of code, but I am able to get the attribute fine, and newIndex is updated properly, but then when I go to change the attribute called count it doesn't do anything.

XmlElement reports = (XmlElement)doc.SelectSingleNode("//Reports");
XmlAttribute reportCount = (XmlAttribute)doc.SelectSingleNode("//Reports/@count");
int count = Convert.ToInt32(reportCount.Value);
newIndex = count + 1;
//doc.DocumentElement.SetAttribute("count", "\"" + newIndex.ToString() + "\"");
//reportCount.Value = newIndex.ToString();
reports.SetAttribute("count", newIndex.ToString());

XML File

<?xml version="1.0" encoding="utf-8"?>
<Reports count="1"><!--this count should be equal to the last id-->
  <Report id="1">
    <Workbook>APG0214.xlsx</Workbook>
    <Filepath>\\fileserver\homeshares\POS Reports</Filepath>
  </Report>
  <Report id="2">
    <Workbook>CBM0214.xlsx</Workbook>
    <Filepath>\\fileserver\homeshares\POS Reports</Filepath>
  </Report>
</Reports>

Any help is appreciated!

1

3 Answers 3

2

I'm not familiar with old XML API but I would use LINQ to XML in this case:

var xmlDocument = XDocument.Load("path");
var reports = xmlDocument.Root;
var maxId = reports
            .Elements("Report")
            .Select(x => (int)x.Attribute("id"))
            .Max();
reports.Attribute("count").SetValue(maxId);
xmlDocument.Save("path");
Sign up to request clarification or add additional context in comments.

1 Comment

Not the reason for the issue, but I do like the answer syntax.
0

You probably forgot about

doc.Save("your_path_to_xml_file")

at the end ;)

1 Comment

I hate myself for asking this question now... this method of mine is for adding an element to the XML file, and I add it using XPath, but I get this using a regular XmlDocument, so in the end I save the XPath version, but not the XmlDocument version. And I knew this, and was about to say you were wrong, but then I had an epiphany :P
0

Just use the following:

reportCount.Value = newIndex.ToString(CultureInfo.InvariantCulture);

and the save the XML back to the original file (or somewhere new).

2 Comments

what is the cultureInfo for?
Ensures that you write the value consistently regardless of any localisation settings on the executing OS. Not putting it would generate an FxCop warning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.