【问题标题】:Removing XML node删除 XML 节点
【发布时间】:2013-05-04 17:07:59
【问题描述】:

我还有另一项无法完成的任务:我应该解析来自 this site 的 XML,删除所有名称中没有“VIDEO”的节点,然后将其保存到另一个 XML文件。我在阅读和写作方面没有问题,但是删除让我有些困难。我试图做节点 -> 父节点 -> 子节点工作,但它似乎没有用:

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”条件的节点。

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

你能帮帮我吗?

【问题讨论】:

    标签: c# xml xml-parsing


    【解决方案1】:

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

    【讨论】:

    • 非常感谢...到目前为止,我使用 Linq 的次数不多,但它看起来非常简单且功能强大。已接受答案。
    • 我可以再问一个问题吗?我试图将写入更改为控制台,但不知何故它不起作用...foreach(var item in xDoc.XPathSelectElements("//item[(starts-with(title, 'VIDEO:'))]").ToList()) { Console.WriteLine((string) item.Attribute("title")); }
    • @Storm title 不是项目的属性。它是子元素。试试item.Element("title").Value
    • 我现在明白了。再次感谢。
    猜你喜欢
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    相关资源
    最近更新 更多