Linq XML动态构建

Eri*_*Cal 1 c# xml linq linq-to-xml

我正在构建一个xml文件.该文件的一部分是静态的.一些文件是动态的.我的代码有一个"空对象引用"错误.

任何提示都会很棒.

private XElement BuildDataElement()
{
    // this is going to be more complicated
    return new XElement("data");
}

public void TestXML(string fname)
{
    // build the data element
    XElement allData = BuildDataElement();

    // Build the header
    XDocument doc = new XDocument(
        new XElement("map",
            new XAttribute("showLabels", "1"),
            new XAttribute("includeNameInLabels", "1"),
            new XElement("colorRange",
                new XElement("color",
                new XAttribute("minValue", "1")
                )
            ),
            allData,
            new XElement("application",
                new XElement("apply",
                    new XAttribute("toObject", "TOOLTIP"),
                    new XAttribute("styles", "TTipFont,MyDataPlotStyle")
                )
            )
         )
     );

    if (File.Exists(fname))
        File.Delete(fname);
    doc.Save(fname);
         }
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 7

任何提示都会很棒.

你说对了.这是我的提示:

  • 获取调试器.
  • 将调试器设置为在所有异常处断开.
  • 在调试器中运行代码,直到发生null引用异常.
  • 找出哪些值为null,您不希望为null.
  • 插入一个null的检查,以处理正确值为null的情况,或者更改逻辑,使该值不可能为null.
  • 彻底的代码审查和测试修复.
  • 为您的测试套件编写一个回归测试,以验证此错误是否会返回.