0

I got a problem when insert XML element using LINQ. This is my program:

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())));
}

Catched error: NullReferenceException unhandled in EditXml() function. Can you guys help me fix that? Thanks so much! :)

Steven
  • 166,672
  • 24
  • 332
  • 435
Chelsea_cole
  • 1,055
  • 3
  • 15
  • 21

3 Answers3

2

You've got a typo in EditXml:

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

You don't have a "chanel" element - you have a "channel" element.

However, you should also be using the right namespace for the RSS feed - the code you've given so far doesn't include any namespaces.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

First thing you should check I think is that doc is not null.

In other words is the CreateXml() function called before HandlingData()?

Hope it helps.

sTodorov
  • 5,435
  • 5
  • 35
  • 55
1

You spelled channel wrong in the EditXml() method.

Chris Gessler
  • 22,727
  • 7
  • 57
  • 83