使用XDocument在C#中向xml文件添加元素

时间:2014-06-01 19:33:07

标签: c# xml linq-to-xml xelement xattribute

这是我目前的XML结构

<root>
<sublist>
    <sub a="test" b="test" c="test"></sub>
  </sublist>
</root>

我使用以下C#但在尝试执行时出错

 public static void writeSub(string a,string b,string c)
        {
            XDocument xDoc = XDocument.Load(sourceFile);
            XElement root = new XElement("sub");
            root.Add(new XAttribute("a", a), new XAttribute("b", b),
                         new XAttribute("c", c));
            xDoc.Element("sub").Add(root);
            xDoc.Save(sourceFile);
        }

我在哪里弄错了?

错误是

nullreferenceexception was unhandled

1 个答案:

答案 0 :(得分:0)

您遇到问题,因为sub不是文档的根元素。所以,当你做的时候

xDoc.Element("sub").Add(root);

然后xDoc.Element("sub")返回null。然后,当您尝试调用方法Add时,您拥有NullReferenceException

我认为您需要向sub元素添加新的sublist元素:

xDoc.Root.Element("sublist").Add(root);

我还建议改进命名。如果您要创建元素sub,请调用varibale sub,而不是将其命名为root(这非常令人困惑)。 E.g。

XDocument xdoc = XDocument.Load(sourceFile);
var sub = new XElement("sub", 
               new XAttribute("a", a), 
               new XAttribute("b", b),
               new XAttribute("c", c));

xdoc.Root.Element("sublist").Add(sub);
xdoc.Save(sourceFile);
相关问题