【问题标题】:How to change an attribute in XML C#如何更改 XML C# 中的属性
【发布时间】:2014-05-20 07:26:55
【问题描述】:

我尝试了几种方法,但似乎都不起作用...

您可以通过查看注释的代码行来查看我尝试过的不同方法,但是我能够很好地获取属性,并且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>

感谢任何帮助!

【问题讨论】:

标签: c# xml


【解决方案1】:

我不熟悉旧的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");

【讨论】:

  • 不是问题的原因,但我确实喜欢答案语法。
【解决方案2】:

只需使用以下内容:

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

并将 XML 保存回原始文件(或新文件)。

【讨论】:

  • cultureInfo 是干什么用的?
  • 确保您始终如一地写入值,而不管执行操作系统上的任何本地化设置。不放它会产生一个 FxCop 警告。
【解决方案3】:

你可能忘记了

doc.Save("your_path_to_xml_file")

最后;)

【讨论】:

  • 我讨厌自己现在问这个问题...我的这个方法是向 XML 文件添加一个元素,我使用 XPath 添加它,但我使用常规 XmlDocument ,所以最后我保存了 XPath 版本,而不是 XmlDocument 版本。我知道这一点,并且正要说你错了,但后来我顿悟了:P
猜你喜欢
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 2015-03-22
相关资源
最近更新 更多