0

这是我更改 XML 元素属性值的方法:

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    XDocument xml = null;
    using (IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Stats_file.xml", FileMode.Open, FileAccess.Read))
    {
       xml = XDocument.Load(isoFileStream, LoadOptions.None);
       xml.Element("statrecords").SetElementValue("value", "2"); //nullreferenceexception
    }
    using (IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Stats_file.xml", FileMode.Truncate, FileAccess.Write))
    {
       xml.Save(isoFileStream, SaveOptions.None);
    }
}

在第 7 行我有 NullReferenceException。你知道如何无误地改变价值吗?

这是我的 XML 文件:

<?xml version='1.0' encoding='utf-8' ?>
<stats>
    <statmoney index='1' value='0' alt='all money' />
    <statrecords index='2' value='0' alt='all completed records' />
</stats>
4

2 回答 2

1

有两个问题。

你得到 a 的原因NullReferenceExceptionxml.Element("statrecords")它将尝试找到一个名为的statrecords元素,而根元素被称为stats

第二个问题是你试图设置一个元素值,而你想改变一个属性值,所以你应该使用SetAttributeValue.

我想你想要:

xml.Root.Element("statrecords").SetAttributeValue("value", 2);

编辑:我给出的代码适用于您提供的示例 XML。例如:

using System;
using System.Xml.Linq;

class Program
{
    static void Main(string[] args)
    {
        var xml = XDocument.Load("test.xml");
        xml.Root.Element("statrecords").SetAttributeValue("value", 2);
        Console.WriteLine(xml);
    }    
}

输出:

<stats>
  <statmoney index="1" value="0" alt="all money" />
  <statrecords index="2" value="2" alt="all completed records" />
</stats>
于 2013-01-28T15:18:04.517 回答
0

如果您xml.Element()在这种情况下使用,您将获得根元素。所以你应该使用Descendants()SetAttributeValue()方法:

var elements = xml.Descendants( "stats" ).Elements( "statrecords" ).ToList(); 
//becuase you can have multiple statrecords
elements[0].SetAttributeValue("value", "2" ); 
于 2013-01-28T15:48:07.240 回答