C#:获取具有所有父标记的XML节点内容 [英] C#: Get XML node content with all parent tags

查看:187
本文介绍了C#:获取具有所有父标记的XML节点内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个XML文件:

<favorites>
    <movies>
        <movie title="The Godfather" year="1974" />
        <movie title="The Terminator" year="1984" />
        <movie title="Dark Knight" year="2008" />
    </movies>

    <books>
        <book title = "1984" author="George Orwell" />
        <book title = "Robinson Crusoe"" author="Daniel Defoe"/>
        <book title = "Frankenstein" author="Mary Shelly" />
    </books>

    <music>
        <artist title = "Beatles" genre="rock" />
        <artist title = "Queen" genre="rock" />
        <artist title = "Metallica" rock="heavy metal" />
    </music>
</favorites>

我需要使用所有父级&过滤特定的节点(音乐)节点. 结果应该是:

I need to filter a specific node (music) with all parent & child nodes. The result should be:

<favorites>
  <music>
    <artist title="Beatles" genre="rock" />
    <artist title="Queen" genre="rock" />
    <artist title="Metallica" rock="heavy metal" />
  </music>
</favorites>

我找到了使用System.XML&过滤XML的解决方案. LINQ:

I've found a solution to filter XML using System.XML & LINQ:

 XDocument xdoc = XDocument.Parse(xmlString);    
 xdoc.Descendants()
     .Where(x => x.Name != "favorites" & x.Name != "music" & x.Name != "artist")
     .Remove();    
 Console.WriteLine(xdoc.ToString());

工作示例在这里: https://dotnetfiddle.net/NnA4h7#

问题是我必须指定所有父级&我的查询中的子节点.

The problem is that I have to specify all parent & child nodes in my query.

是否可以通过仅指定一个想要的节点(电影,书籍,音乐)来获得相同的结果?

Is there a way to get the same result with specifying a wanted node only (movies, books, music) ?

推荐答案

这是另一种更简单的方法:

Here is another method that is a little simpler :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement favorites = doc.Descendants("favorites").FirstOrDefault();

            favorites.ReplaceNodes(favorites.Element("music")));
        }
    }
}

这篇关于C#:获取具有所有父标记的XML节点内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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