c# - 对象引用未设置为对象 xml C# 的实例并使用 C# 在 xml 文件中添加一些节点

标签 c# .net xml

这是在 C# 中使用 xml 的简单代码。我想添加这样的数据

<table1 name="something">
   <column1 someattribute="something"> actualname </column>
</table1>

然后我想将此元素添加到 XDocument 的对象中

XDocument document;
public Form1()
{
   InitializeComponent();
   document = new XDocument();
}

private void button1_Click(object sender, EventArgs e)
{
  //document = new XDocument();
   XElement elem = new XElement("table1");
   elem.Add(new XAttribute("TableName", textBox1.Text));
   elem.Add(new XElement("Column1",new XAttribute("Someattribute", somevalue));
   document.Element("table1").Add(elem);//throws exception object refernce not set ..."
}

我试过下面的代码Adding elements to an xml file in C#但它抛出“对象引用未设置到对象 xml C# 的实例”的异常 请帮忙 P.S: 假设 table1 中有很多列,那么首先我想累加每一列,然后将其添加到 xdocument 中,然后是 table2,我想对他做同样的事情。

最佳答案

您的 XML 结构中没有 table1 元素。这意味着您的 document.Element("table1") 表返回 null,因此当您调用 .Add(elem) 在上面。

大多数情况下,调试 NullReferenceExceptions 是非常基本的,只需使用调试器单步调试代码即可轻松解决这些问题。

作为引用,Element 方法

Gets the first (in document order) child element with the specified XName.

这就是为什么你得到一个 null。 ( MSDN )

初始化表单时,您创建了一个空文档,如 new XDocument()。然后,在单击按钮时,您尝试使用选择器 document.Element("table1")< 添加一个新元素 作为 table1 的子元素。这就是问题所在,您的 XDocument 是空的!您需要先创建一个 table1 元素,或者将您的 elem 对象直接添加到文档中。

这意味着您可以这样做以确保 table1 存在:

document = XDocument.Parse("<table1></table1>);

或更改您的点击方法以将目录添加到文档的根目录:

private void button1_Click(object sender, EventArgs e)
{
  //document = new XDocument();
   XElement elem = new XElement("table1");
   elem.Add(new XAttribute("TableName", textBox1.Text));
   elem.Add(new XElement("Column1",new XAttribute("Someattribute", somevalue)));
   document.Add(elem);
}

关于c# - 对象引用未设置为对象 xml C# 的实例并使用 C# 在 xml 文件中添加一些节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645924/

相关文章:

c# - LINQ lambda 表达式附加 OR 语句

c# - 有没有办法编写一个表示构造函数参数的表达式?

c# - Nhibernate CommitAsync 是否等待所有异步 CRUD 操作?

c# - 数据集更新与 SQL 查询

php强制下载xml

python - Python 的方式是什么来表达在 XML 文档中根据需要创建尽可能多的标签的 GREL 行?

c# - 左加入 Linq 查询

c# - 是否有适用于 Linux 的 C#?

C# 类型推断 : fails where it shouldn't?

java - JAXB 可以在基类中初始化值吗?