我有一个XMLNode item
要附加到XMLNode targetNode
的{{1}}
XMLDocument docRss
异常:对象引用未设置为对象的实例。
编辑我发现 targetNode为空,但为什么?,如docRss.innerXml中显示它的当前
在此声明价值之前:
XmlNode targetNode = docRss.SelectSingleNode("channel");
targetNode .AppendChild(docRss.ImportNode(item, true));
答案 0 :(得分:2)
看起来您正在尝试操纵RSS Feed。使用System.ServiceModel.Syndication命名空间的成员不会消除很多痛点吗? SyndicationFeed和Rss20FeedFormatter,例如......
要向Feed中添加节点,请尝试此操作...
void RetargetFeed()
{
string feedLocation = "http://example.com/rssfeed";
// read original feed
Rss20FeedFormatter rssformat = new Rss20FeedFormatter();
rssformat.ReadFrom(XmlReader.Create(feedLocation));
// create a list of items from the rogiinal
List<SyndicationItem> items = new List<SyndicationItem>();
items.AddRange(rssformat.Feed.Items);
// add a new item to the end of the list
items.Add(new SyndicationItem("Test Item", "This is the content for Test Item", new Uri("http://Contoso/ItemOne"), "TestItemID", DateTime.Now));
// create a new Rss writer
SyndicationFeed newFeed = new SyndicationFeed(items);
var writeFormat = new Rss20FeedFormatter(newFeed);
//and write the output to a file
writeFormat.WriteTo(XmlWriter.Create("testoutputfile.xml"));
}
答案 1 :(得分:1)
targetNode
为空,所以我选错了它必须被选为
XmlNode channel = docRss.SelectSingleNode("rss/channel");