简体   繁体   English

如何在XML C#中更改属性

[英]How to change an attribute in XML C#

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

Any help is appreciated! 任何帮助表示赞赏!

I'm not familiar with old XML API but I would use LINQ to XML in this case: 我不熟悉旧的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");

Just use the following: 只需使用以下内容:

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

and the save the XML back to the original file (or somewhere new). 然后将XML保存回原始文件(或新位置)。

You probably forgot about 你可能忘了

doc.Save("your_path_to_xml_file") doc.Save( “your_path_to_xml_file”)

at the end ;) 在末尾 ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM