【问题标题】:Insert XML element using LINQ使用 LINQ 插入 XML 元素
【发布时间】:2011-07-10 14:09:25
【问题描述】:

我在使用 LINQ 插入 XML 元素时遇到问题。这是我的程序:

XDocument doc;

protected void CreateXml()
{
    doc = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"),
        new XComment("Sample RSS Feed"),
        new XElement("rss",
            new XAttribute("version", "2.0"),
            new XElement("channel",
                new XElement("title", "aaa"),
                new XElement("description", "bbb"),
                new XElement("link", "http://abcd.com"),
                new XElement("language", "en"))
            )
        );
}

protected void HandlingData()
{
    //...
    EditXml();
}

protected void EditXml()
{
    doc.Element("rss").Element("chanel")
        .Element("language").AddAfterSelf(
            new XElement("item", new XElement("title", "ccc"),
            new XElement("link","..."),
            new XElement("pubDate", 
                DateTime.Now.ToUniversalTime())));
}

捕获的错误:NullReferenceException 未处理 在 EditXml() 函数中。你们能帮我解决这个问题吗?非常感谢! :)

【问题讨论】:

    标签: c# xml linq xelement


    【解决方案1】:

    您在EditXml 中有错字:

    doc.Element("rss").Element("chanel")...
    

    你没有“chanel”元素——你有一个“channel”元素。

    但是,您还应该为 RSS 提要使用正确的命名空间 - 您目前提供的代码不包含任何命名空间。

    【讨论】:

      【解决方案2】:

      我认为您应该检查的第一件事是doc 不为空。

      也就是说CreateXml()函数是在HandlingData()之前调用的吗?

      希望对你有帮助。

      【讨论】:

        【解决方案3】:

        您在 EditXml() 方法中拼错了频道。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多