【发布时间】: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