Chelsea_cole
Chelsea_cole

Reputation: 1095

Insert XML element using LINQ

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! :)

Upvotes: 0

Views: 782

Answers (3)

Chris Gessler
Chris Gessler

Reputation: 23113

You spelled channel wrong in the EditXml() method.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500495

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.

Upvotes: 2

sTodorov
sTodorov

Reputation: 5461

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.

Upvotes: 1

Related Questions