【发布时间】:2012-02-07 00:45:48
【问题描述】:
问题是我有一个 xml 文件,我试图将数据附加到该文件中。我正在使用 LINQ to XML,我使用的代码如下:
public void AppendSalesXMLData(Company company)
{
string FileName = "TestSales";
string OrgID = company.OrgID.ToString();
string SaleID = company.OrgSales[company.OrgSales.Count - 1].SaleID.ToString();
if (!File.Exists(String.Format(@"C:\Data-Source\trunk\Applications\VintageSiteInspector\XML\{0}.xml", FileName)))
{
CreateXMLFile(FileName);
}
XDocument thisDoc = XDocument.Load(String.Format(@"C:\Data-Source\trunk\Applications\VintageSiteInspector\XML\{0}.xml", FileName));
<!------- The following line throws an exception every time. ----->
thisDoc.Element(FileName).Add(new XElement("Sale"));
thisDoc.Save(String.Format(@"C:\Data-Source\trunk\Applications\VintageSiteInspector\XML\{0}.xml", FileName));
}
我打开的 XML 文件是
<?xml version="1.0" encoding="utf-8"?>
<root>
<TestSales></TestSales>
</root>
我只是不明白为什么会出现空引用异常。
【问题讨论】:
-
哪个对象/哪个部分在调用异常?
-
@JamieKeeling :)
-
假设您的文件名为“Test”,那么 xml 中是否有一个名为“Test”的元素?如果您尝试将 XElement 添加到 xml,那么我想您需要执行类似 thisDoc.Add(new XElement("Sale")); 的操作
-
用元素值试试这个 -- thisDoc.Element(FileName).Add(new XElement("Sale","SaleValue"));
-
@CBRRacer 我错了,谢谢!
标签: c# xml winforms linq linq-to-xml