如何修复'System.NullReferenceException:'对象引用未设置为对象的实例。'

时间:2019-05-29 07:09:20

标签: c# linq-to-xml

我是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>

谢谢

1 个答案:

答案 0 :(得分:0)

StudentStudents之间还有一个Student-101元素。看起来您的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,它可以正常工作。