【问题标题】:NullReferenceException when changing XML element attribute value更改 XML 元素属性值时出现 NullReferenceException
【发布时间】:2013-01-28 15:15:26
【问题描述】:

这是我更改 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>

【问题讨论】:

  • “statrecords”是否存在?

标签: c# xml windows-phone-7 nullreferenceexception isolatedstorage


【解决方案1】:

有两个问题。

您获得NullReferenceException 的原因是xml.Element("statrecords") 将尝试查找名为statrecords 元素,而根元素称为stats

第二个问题是你试图设置一个 element 值,而你想改变一个 attribute 值,所以你应该使用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>

【讨论】:

  • 谢谢,但仍然是例外。如果您知道更改此值的其他方法,请与我分享:)
  • @ŁukaszWróblewski:“它仍然例外”不足以帮助您。什么例外?在哪里?你能发布一个简短但完整的程序来演示这个问题吗?您做了多少诊断?
【解决方案2】:

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

var elements = xml.Descendants( "stats" ).Elements( "statrecords" ).ToList(); 
//becuase you can have multiple statrecords
elements[0].SetAttributeValue("value", "2" ); 

【讨论】:

  • 我有这个错误:无法使用 [] 将索引应用于“System.Collections.Generic.IEnumerable”类型的表达式
  • 感谢您的回复,请检查:img803.imageshack.us/img803/1996/errorgl.png
  • 这意味着列表中没有元素。我测试了我的代码并且它可以工作,所以你确定你正在加载正确的 xml 文件并且它包含那个节点吗?
  • 我已将“statrecords”元素和“statmoney”元素都更改为“stat”,并将代码更改为“elements[1]”。感谢您的帮助,它有效:)
  • 这里不需要使用Descendants,或者Elements。如果 XML 如 OP 的问题所示,使用 xml.Root.Element 应该 可以正常工作(而且更简单)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
相关资源
最近更新 更多