C# & XML - 对象引用未设置为对象的实例

本文关键字:设置 对象 实例 对象引用 amp XML | 更新日期: 2023-09-27 18:31:31

晚安堆叠花朵,
我最近开始通过Visual Studio 2010进行XML编码。我遇到了看似简单的解决方案,但解决方案逃脱了我。我收到未设置对象引用的错误,但我看不到未设置的内容。(此处错误:https://i.stack.imgur.com/CDZgG.png)

我的代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
public partial class _Default : System.Web.UI.Page
  {
    int intDVDID;
    XmlDocument myXmlDocument = new XmlDocument();
    XmlNode rootNode;
    XmlNode selectedDVD;
public void Page_Load(object Src, EventArgs E)
{
    intDVDID = Convert.ToInt32(Request.QueryString["id"]);
    myXmlDocument.Load(Request.PhysicalApplicationPath + @"dvd.xml");
    rootNode = myXmlDocument.DocumentElement;
    selectedDVD = rootNode.ChildNodes[intDVDID - 1];
    if (!Page.IsPostBack)
    {
        rootNode.RemoveChild(selectedDVD);
        myXmlDocument.Save(Request.PhysicalApplicationPath + @"dvd.xml");
        lblMessage.Text = "You have successfully deleted the DVD";
    }
  }
}

只是说:

  int intDVDID = new intDVDID 

我知道通过阅读本文,你们都会想因为我缺乏经验和缺乏如何解决这个问题而拔头发,但我感谢您的时间和耐心。

此致敬意劳拉·:)

编辑:这是我的 XML:

<?xml version="1.0" encoding="utf-8" ?>
<!-- This XML document describes a DVD library -->
<library>
  <DVD id="1">
    <title>Breakfast at Tiffany's</title>
    <format>Movie</format>
    <genre>Classic</genre>
  </DVD>
  <DVD id="2">
    <title>Contact</title>
    <format>Movie</format>
    <genre>Science fiction</genre>
  </DVD>
  <DVD id="3">
    <title>Little Britain</title>
    <format>TV Series</format>
    <genre>Comedy</genre>
  </DVD>
</library>

C# & XML - 对象引用未设置为对象的实例

看起来您选择的DVD可能为空,请进行一些空检查以进行验证。

if(selectedDVD != null)
{
}

编辑:在评论中回答您的问题。下面是一些示例代码。我扔了一个 xpath,即使看起来你的情况很简单,你可能想在未来使用它

string xml = "<xml><node id='1'></node><node id='2'></node></xml>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);           
//This is an xpath(This replaces your .DocumentElement.ChildNodes[index]
XmlNode desiredNode = xmlDoc.DocumentElement.SelectSingleNode("node[@id='1']");
if (desiredNode != null)
{
    xmlDoc.DocumentElement.RemoveChild(desiredNode);
}//if             
请确保您的

查询字符串不为空,这可能会导致您获得的空引用执行。

if(Request.QueryString["id"]!="")
{
    intDVDID = Convert.ToInt32(Request.QueryString["id"]);
}