2017-11-11 124 views
0

我一直在这里研究XML在SO。我试着用XDocument在里面添加一个节点。孩子不在节点XML C追加#

我的XML看起来像这样

<root> 
    <parent> 

    </parent> 
</root> 

和预期XML应该像

<root> 
    <parent> 
    <course>ABC</course> 
    <credit>555</credit> 
    </parent> 
</root> 

我写了这个代码实现

XDocument xml = XDocument.Load("root.xml"); 
XElement root = xml.Root.Element("root"); 
root.Element("parent").Add(new XElement("course", "ABC")); 

但在3号线它给

未将对象引用设置为对象的实例。

任何一个可以帮助解释吗?

回答

3

XDocument.Root是您的文档中的根元素,在您的情况下是“root”。

因此

xml.Root.Element("root"); 

正在寻找您的根元素的子元素的 “根”,即:

<root> 
    <root> 
    ... 

这不存在,因此您的空引用。

试试这个:

xml.Root.Element("parent").Add(new XElement("course", "ABC")); 
+0

这是不添加任何。 – Alen

+0

现在工作!我的错。谢谢 – Alen

1

这工作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument xml = XDocument.Load(FILENAME); 

      XElement parent = xml.Descendants("parent").FirstOrDefault(); 

      parent.Add(new object[] { 
       new XElement("course", "ABC"), 
       new XElement("credit",555) 
      }); 
     } 
    } 
}