【问题标题】:Linq XML Dynamic buildingLinq XML 动态构建
【发布时间】:2026-02-14 05:50:01
【问题描述】:

我正在构建一个 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);
         }

【问题讨论】:

  • 我不明白为什么你会在该代码中得到 NullReferenceException。请提供一个简短但完整的程序来演示该问题。
  • 您提供的代码在 LINQPad 中对我来说运行得很好。也许您将一个空文件名传递给 TestXML?

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


【解决方案1】:

任何提示都会很棒。

你明白了。以下是我的建议:

  • 获取调试器。
  • 将调试器设置为在所有异常时中断。
  • 在调试器中运行您的代码,直到发生空引用异常。
  • 找出您不希望为 null 的值为 null 的值。
  • 要么插入对 null 的检查以正确处理值为 null 的情况,要么更改逻辑以使该值不可能为 null。
  • 彻底的代码审查和测试修复。
  • 为您的测试套件编写回归测试,以验证此错误不会再次出现。

【讨论】:

  • 同意,首先使用调试器找出错误所在的行,而不是发布整个方法。
【解决方案2】:

在 sn-p 中,我可以看到出现错误的唯一方法是 2 两个地方。

BuildDataElement();

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

接下来如果BuildDataElement(); 返回,那可能是问题所在,因为我猜测 XDocument 正在执行.ToString() 或对allData 执行某些操作

【讨论】: