2

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();
        }
    }

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();
}

Could you help me, please?

4

1 回答 1

2

我发现 Linq To Xml 更易于使用

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();             
}
于 2013-05-04T17:26:43.917 回答