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!

Adjit
  • 10,134
  • 12
  • 53
  • 98
  • Have you looked at this post yet? http://stackoverflow.com/questions/367730/how-to-change-xml-attribute?rq=1 – Josh Jay Apr 07 '14 at 20:55

3 Answers3

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");
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

Just use the following:

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

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

Martin Costello
  • 9,672
  • 5
  • 60
  • 72
0

You probably forgot about

doc.Save("your_path_to_xml_file")

at the end ;)

a''
  • 2,322
  • 2
  • 23
  • 34
  • 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 – Adjit Apr 07 '14 at 21:07