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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

You spelled channel wrong in the EditXml() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.