更改 XML 元素属性值时的 NullReferenceException
本文关键字:NullReferenceException 属性 XML 元素 更改 | 更新日期: 2023-09-27 17:56:33
这是我更改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>
有两个问题。
您获得NullReferenceException
的原因是xml.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>
如果在这种情况下使用 xml.Element()
,则会获得根元素。因此,您应该使用Descendants()
和SetAttributeValue()
方法:
var elements = xml.Descendants( "stats" ).Elements( "statrecords" ).ToList();
//becuase you can have multiple statrecords
elements[0].SetAttributeValue("value", "2" );