这是在 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/