【问题标题】:Adding elements to xml file in C# using XDocument [duplicate]使用 XDocument 在 C# 中将元素添加到 xml 文件 [重复]
【发布时间】:2014-07-21 22:16:58
【问题描述】:

这是我当前的 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

【问题讨论】:

  • 使用调试器找出什么是空的。
  • 你认为xDoc.Element("sub")是什么?

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


【解决方案1】:

您有问题,因为sub 不是文档的根元素。所以,当你这样做时

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

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

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

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

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

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

【讨论】:

  • thx,它有效,但最后我得到 而不是
  • 这些定义没有区别。您可以尝试提供空字符串作为 sub 元素的值以获得所需的结果(抱歉,无法在此处验证此建议)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多