【问题标题】:How to fix 'System.NullReferenceException: 'Object reference not set to an instance of an object.'如何修复'System.NullReferenceException:'对象引用未设置为对象的实例。
【发布时间】:2019-05-29 07:09:19
【问题描述】:

我是 Xml 和 Linq 的新手,我一直在关注 youtube 上关于如何使用它的教程。

视频链接:https://www.youtube.com/watch?v=OsfVJ485RY4

问题是当我运行代码来更改值或删除它时,我总是收到以下错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XElement.Attribute(...) returned null.

首先我加载我的文档:

XDocument xmlDocument = XDocument.Load(@"C:\Users\matpl\source\repos\LinqToXML\LinqToXML\Data.xml");

我要更改Xml文档值的部分

xmlDocument.Element("Students")
           .Elements("Student")
           .Where(x => x.Attribute("Id").Value == "101").FirstOrDefault()
           .SetElementValue("TotalMarks", "999");

当我想删除一个元素时:

xmlDocument.Root.Elements().Where(x => x.Attribute("Id").Value == "104").Remove();

XML 文件:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Comment Updated-->
<Students>
  <Student>
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student>
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>

谢谢,

【问题讨论】:

  • 最好的方法是一步一步检查。首先在学生元素上,然后在学生等中,直到你的变量为空。顺便说一句,我认为你有两次学生元素,所以它在第一个上停止,而你想通过第二个。

标签: c# linq-to-xml


【解决方案1】:

StudentsStudent-101 之间还有一个Student 元素。看起来你的 xml 有误:

<Students>
  <Student> //WHAT IS IT?
    <Student Id='101'>
      <Name>Mark</Name>
      <Gender>Male</Gender>
      <TotalMarks>800</TotalMarks>
    </Student>
    <Student Id='102'>
      <Name>Rosy</Name>
      <Gender>Female</Gender>
      <TotalMarks>900</TotalMarks>
    </Student>
    <Student Id='103'>
      <Name>Pam</Name>
      <Gender>Female</Gender>
      <TotalMarks>850</TotalMarks>
    </Student>
    <Student Id='104'>
      <Name>John</Name>
      <Gender>Male</Gender>
      <TotalMarks>950</TotalMarks>
    </Student>
  </Student> //WHAT IS IT?
  <Student Id='105'>
    <Name>Todd</Name>
    <Gender>Male</Gender>
    <TotalMarks>980</TotalMarks>
  </Student>
</Students>

检查此https://dotnetfiddle.net/14js9r。使用正确的 xml 可以正常工作。

【讨论】:

  • 谢谢,我一直在看我的代码而不是我的 xml 文档,删除两个错误的行解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多