开发者

Insert XML element using LINQ

开发者 https://www.devze.com 2023-03-19 08:57 出处:网络
I got a problem when insert XML element using LINQ. This is my program: XDocument doc; protected void CreateXml()

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 XE开发者_C百科lement("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! :)


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.


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.


You spelled channel wrong in the EditXml() method.

0

精彩评论

暂无评论...
验证码 换一张
取 消