【问题标题】:LINQ to XML Append Data throws null reference exceptionLINQ to XML Append Data 引发空引用异常
【发布时间】: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


【解决方案1】:

Element 指的是直接孩子(在您的情况下是root,而不是TestSale)。改用Descendants

thisDoc.Descendants(FileName).First().Add(new XElement("Sale"));

或者,当您了解 XML 树时,您也可以像这样简单地遍历它:

thisDoc.Element("root").Element(FileName).Add(new XElement("Sale"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2012-09-29
    • 2011-01-25
    • 2012-10-29
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多