簡體   English   中英

如何在XML C#中更改屬性

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

我嘗試了幾種方法,但似乎都不起作用...

您可以通過看一下代碼的注釋行來查看嘗試過的不同方法,但是我可以很好地獲取屬性,並且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>

任何幫助表示贊賞!

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

只需使用以下內容:

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

然后將XML保存回原始文件(或新位置)。

你可能忘了

doc.Save( “your_path_to_xml_file”)

在末尾 ;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM