繁体   English   中英

如何使用 C# 递归打印 xml 树属性和元素?

[英]How to recursively print xml tree attributes and elements using C#?

我有以下 xml 文件,需要将作者的属性和子元素存储在变量中,并在控制台上打印出来。 所以基本上:id、obs 和负责人以及 FIRSTNAME 和 LASTNAME 需要存储为变量并打印到控制台。

    <AUTHORS>
        <AUTHOR id='_03131488' obs='0' responsible='1'>
            <LASTNAME>Richard</LASTNAME>
            <FIRSTNAME>Dickson</FIRSTNAME>
        </AUTHOR>
        <AUTHOR id='_03135122' obs='0'>
            <LASTNAME>Carlo</LASTNAME>
            <FIRSTNAME>Ancelotti</FIRSTNAME>
        </AUTHOR>
        <AUTHOR id='_0312C456' obs='0' responsible='1'>
            <LASTNAME>Patricia</LASTNAME>
            <FIRSTNAME>Howard</FIRSTNAME>
        </AUTHOR>
    </AUTHORS>

我为它编写了以下代码,但不知何故它根本不会打印到控制台。

    class Solution
    {
        public static string xmlFilePath = "authors.xml";
    
        public static void Main()
        {
            XDocument doc = XDocument.Load(xmlFilePath);
            List<Author> authors = LoadAuthors(doc.Descendants("AUTHOR")
                .Elements("AUTHORS"));
        }
    
        public static List<Author> LoadAuthors(IEnumerable<XElement> authors)
        {
            return authors.Select(x => new Author()
            {
                FirstName = x.Attribute("FIRSTNAME").Value,
                LastName = x.Attribute("LASTNAME").Value,
                Children = LoadAuthors(x.Elements("AUTHORS"))
            }).ToList();
        }
    
        public void PrintAutors()
        {
            foreach (Author author in authors)
            {
                Console.WriteLine(author.ToString());
            }
        }
    }

    public class Author
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Author> Children { get; set; }
    
        public override string ToString()
        {
            return $"{FirstName}, {LastName}\n{Children
                .Select(c => c.ToString())
                .Aggregate((a, b) => a + "\n" + b)}";
        }
    }

有人可以帮助我将值正确存储到变量中并将它们打印到控制台吗?

“@Charlieface 我是 C# 新手,所以我对如何在 main 方法中调用该调用感到困惑?”

它可能看起来像以下两个修改:

        public static void Main()
        {
            XDocument doc = XDocument.Load(xmlFilePath);
            List<Author> authors = LoadAuthors(doc.Descendants("AUTHOR")
                .Elements("AUTHORS"));
            // New Line in Main() as suggested by @Charlieface
            PrintAutors(authors); 
        }

        // so that the signature of PrintAutors() would change a little
        private static void PrintAutors(IList<Author> authors)
        {
            foreach (Author author in authors)
            {
                Console.WriteLine(author.ToString());
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM