开发者

Linq XML Dynamic building

I am building an xml file. 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.
  • 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.
  • 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.

BuildDataElement();

Could be generating the error, rather than the Xml document.

Next if BuildDataElement(); returns that might be the problem, since I am guessing the XDocument is doing a .ToString() or some action on allData

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜