删除 XML 节点

Removing XML node(删除 XML 节点)
本文介绍了删除 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("
Done...");

            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 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)