C# 使用Linq编辑元素的多个子体
我试图了解如何使用LINQ编辑元素的多个子元素。当我尝试这样做时,我能够成功地更改第一个元素的值,但在第二个元素上我无法更改,因为它会引发以下错误: System.NullReferenceException:'对象引用未设置为 对象的实例。” 我的xml文档中包含以下内容:C# 使用Linq编辑元素的多个子体,c#,xml,linq,C#,Xml,Linq,我试图了解如何使用LINQ编辑元素的多个子元素。当我尝试这样做时,我能够成功地更改第一个元素的值,但在第二个元素上我无法更改,因为它会引发以下错误: System.NullReferenceException:'对象引用未设置为 对象的实例。” 我的xml文档中包含以下内容: <?xml version="1.0" encoding="utf-16"?> <TestCases> <TestCase> <name>one</name
<?xml version="1.0" encoding="utf-16"?>
<TestCases>
<TestCase>
<name>one</name>
<ticket>biscuit</ticket>
<summary>ok</summary>
<prerequisites>ok</prerequisites>
</TestCase>
<TestCase>
<name>two</name>
<ticket>biscuits</ticket>
<summary>ok</summary>
<prerequisites>ok</prerequisites>
</TestCase>
</TestCases>
LINQ查询是在您枚举它们时延迟执行的。每次您枚举它们时,如果源数据/集合发生了更改,则结果可能会有所不同 在修改元素之前,您需要急切地将查询具体化为一个集合(例如,通过
ToList
):
var q = (from node in doc.Descendants("TestCase")
where node.Element("name").Value == uneditedTestCase.name
select node).ToList();
否则,当您执行
q.Descendants("name").SingleOrDefault().SetValue(Form1.currentTestCase.name);
您正在更改名称,这使得原始查询没有任何匹配项(where node.Element(“name”).Value==uneditedTestCase.name1
对于任何元素都不再为真)
因此,第二次执行查询时,以下内容将为空:
q.Descendants("ticket").SingleOrDefault()
在null上调用
SetValue
会产生一个NullReferenceException。LINQ查询在枚举时被延迟执行。每次您枚举它们时,如果源数据/集合发生了更改,则结果可能会有所不同
在修改元素之前,您需要急切地将查询具体化为一个集合(例如,通过ToList
):
var q = (from node in doc.Descendants("TestCase")
where node.Element("name").Value == uneditedTestCase.name
select node).ToList();
否则,当您执行
q.Descendants("name").SingleOrDefault().SetValue(Form1.currentTestCase.name);
您正在更改名称,这使得原始查询没有任何匹配项(where node.Element(“name”).Value==uneditedTestCase.name1
对于任何元素都不再为真)
因此,第二次执行查询时,以下内容将为空:
q.Descendants("ticket").SingleOrDefault()
在null上调用SetValue
,会产生一个NullReferenceException