[英]Insert XML element using LINQ
使用 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())));
}
捕獲的錯誤:在 EditXml() function 中未處理 NullReferenceException 。 你們能幫我解決這個問題嗎? 非常感謝: :)
您在EditXml
中有錯字:
doc.Element("rss").Element("chanel")...
你沒有“chanel”元素——你有一個“channel”元素。
但是,您還應該為 RSS 提要使用正確的命名空間——到目前為止,您提供的代碼不包含任何命名空間。
我認為你應該檢查的第一件事是doc
不是 null。
換句話說, CreateXml()
function 是在HandlingData()
之前調用的嗎?
希望能幫助到你。
您在 EditXml() 方法中拼寫錯誤的頻道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.