删除XML节点 [英] Removing XML node

查看:65
本文介绍了删除XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还有另一项我无法完成的任务:我应该从此站点,删除名称中没有"VIDEO"的所有节点,然后将其保存到另一个XML文件中.我的阅读和书写没有问题,但是搬走会给我带来一些困难.我已经尝试执行节点->父节点->子节点的工作,但是它似乎没有用:

I have got yet another task I am not able to accomplish: I am supposed to parse the XML from this site, remove all the nodes that don't have "VIDEO" in their name and then save it to another XML file. I have no problems with reading and writing, but removing makes me some difficulties. I have tried to do the Node -> Parent Node -> Child Node work-aroud, but it did not seem useful:

static void Main(string[] args)
    {
        using (WebClient wc = new WebClient())
        {
            string s = wc.DownloadString("http://feeds.bbci.co.uk/news/health/rss.xml");
            XmlElement tbr = null;
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(s);

            foreach (XmlNode node in xml["rss"]["channel"].ChildNodes)
            {
                if (node.Name.Equals("item") && node["title"].InnerText.StartsWith("VIDEO"))
                {
                    Console.WriteLine(node["title"].InnerText);
                }
                else
                {
                    node.ParentNode.RemoveChild(node);
                }
            }

            xml.Save("NewXmlDoc.xml");
            Console.WriteLine("\nDone...");

            Console.Read();
        }
    }

我还尝试了RemoveAll方法,因为它删除了所有不满足"VIDEO"条件的节点,所以该方法也不起作用.

I have also tried the RemoveAll method, which does not work as well, because it removes all the nodes not satisfying the "VIDEO" condition.

//same code as above, just the else statement is changed
else
{
   node.RemoveAll();
}

可以帮我吗?

推荐答案

我发现Linq To Xml更易于使用

I find Linq To Xml easier to use

var xDoc = XDocument.Load("http://feeds.bbci.co.uk/news/health/rss.xml");

xDoc.Descendants("item")
    .Where(item => !item.Element("title").Value.StartsWith("VIDEO"))
    .ToList()
    .ForEach(item=>item.Remove());

xDoc.Save("NewXmlDoc.xml");

您还可以使用 XPath

foreach (var item in xDoc.XPathSelectElements("//item[not(starts-with(title,'VIDEO:'))]")
                         .ToList())
{
    item.Remove();             
}

这篇关于删除XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆