簡體   English   中英

子級未附加到節點XML C#中

[英]Child not appending in a node XML C#

我一直在這里學習XML。 我嘗試使用XDocument在其中添加一個節點。

我的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"));

但是在第三行

你調用的對象是空的。

有人可以幫忙解釋一下嗎?

XDocument.Root是文檔中的根元素,在本例中為“ root”。

因此

xml.Root.Element("root");

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

<root>
    <root>
    ...

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

嘗試這個:

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

這有效:

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)
            });
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM