简体   繁体   English

Linq XML动态构建

[英]Linq XML Dynamic building

I am building an xml file. 我正在构建一个xml文件。 Parts of the file are static. 文件的某些部分是静态的。 Some of the file is dynamic. 一些文件是动态的。 My code has an error of “Null object reference”. 我的代码有一个“空对象引用”的错误。

Any tips would be awesome. 任何提示都会很棒。

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

Any tips would be awesome. 任何提示都会很棒。

You got it. 你说对了。 Here are my tips: 这是我的提示:

  • Obtain a debugger. 获取调试器。
  • Set the debugger to break at all exceptions. 将调试器设置为在所有异常时都中断。
  • Run your code in the debugger until the null reference exception happens. 在调试器中运行代码,直到发生null引用异常。
  • Figure out which value was null that you did not expect to be null. 找出哪个值是您预期不会为空的空值。
  • Either insert a check for null that handles the situation where the value is null correctly, or change the logic so that it becomes impossible for that value to be null. 要么插入一个检查null的值以正确处理该值为null的情况,要么更改逻辑以使该值变为null成为不可能。
  • Thoroughly code-review and test the fix. 彻底检查代码并测试修复程序。
  • Write a regression test for your test suites that verifies that this bug doesn't come back. 为您的测试套件编写回归测试,以验证此错误不会再次出现。

The only way in the snippet provided I can see getting an error would be 2 two places. 提供的片段中,我可以看到得到错误的唯一方法是2个2位。

BuildDataElement();

Could be generating the error, rather than the Xml document. 可能是生成错误,而不是Xml文档。

Next if BuildDataElement(); 下一步,如果BuildDataElement(); returns that might be the problem, since I am guessing the XDocument is doing a .ToString() or some action on allData 返回可能是问题所在,因为我猜XDocument正在对allData执行.ToString()或某些操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM