如何更改XML C#中的属性

时间:2014-04-07 20:50:09

标签: c# xml

我尝试了几种方法,其中没有一种方法可行......

您可以通过查看注释的代码行来查看我尝试过的不同方法,但是我能够正确地获取属性,并且newIndex已正确更新,但是当我去更改时名为count的属性,它没有做任何事情。

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文件

<?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>

感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

我对旧XML API不熟悉,但在这种情况下我会使用LINQ to XML

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");

答案 1 :(得分:0)

只需使用以下内容:

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

并将XML保存回原始文件(或新的某个地方)。

答案 2 :(得分:0)

你可能忘记了

  

doc.Save(&#34; your_path_to_xml_file&#34)

最后;)