2009-10-19 131 views
1

我正在构建一个xml文件。部分文件是静态的。一些文件是动态的。我的代码有一个“空对象引用”的错误。Linq XML Dynamic building

任何提示将是真棒。

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

我看不出为什么你会在该代码中得到NullReferenceException。请提供一个简短但完整的程序来说明问题。 – 2009-10-19 16:29:32

+0

您提供的代码在LINQPad中运行得很好。也许你正在向TestXML传递一个空文件名? – StriplingWarrior 2009-10-19 16:51:59

回答

0

在提供的代码段中,我可以看到发生错误的唯一方法是两个地方。

BuildDataElement(); 

可能是生成错误,而不是Xml文档。

下一页如果BuildDataElement();回报,可能是这个问题,因为我猜的XDocument正在做allData

7

一个.ToString()或一些动作任何提示将真棒。

你明白了。这里是我的提示:

  • 获取一个调试器。
  • 将调试器设置为在所有异常情况下都中断。
  • 在调试器中运行您的代码,直到发生空引用异常。
  • 找出哪些值为空,您不希望为空。
  • 要么插入一个检查null的值,以处理值正确为null的情况,要么更改逻辑值,以使该值无法为空。
  • 彻底的代码审查和测试修复。
  • 为你的测试套件编写一个回归测试,验证这个错误不会回来。
+1

同意,首先找出调试器发生错误的行,而不是发布整个方法。 – 2009-10-19 17:20:09