如何将通用 xml 读入通用层次类

问题描述 投票:0回答:1

基本上我想编写一个通用的 XML 查看器......给定类似的东西:

<Settings>
    <User Name="Terry" BDay="09-01-1966">
        <Spouse>
            <Name>Jerri</Name>
        </Spouse>
    </User>
    <User Name="Cliff" BDay="10-18-1980"/>
</Settings>

并显示如下:

Settings =    
    User =        
        .Name = Terry
        .BDay = 09-01-1966
        Spouse =
            Name = Jerri        
    User =
        .Name = Cliff
        .BDay = 10-18-1980

在标签名称之前用句点标注属性,并且子节点和属性缩进。

我想使用类似的类:

public class XHierarchy
{
    public string Name { get; set; }
    public string Value { get; set; }
    public List<XHierarchy> Items { get; set; } = new List<XHierarchy>();
}

如果我手动创建一些测试数据,我的模型/类可以正常工作。我遇到的问题是弄清楚如何将 xml 文件中的数据读入类中。我希望它适用于任何有效的 xml,而不仅仅是遵循测试数据模式的内容。

c# wpf xml-parsing hierarchy
1个回答
0
投票

尝试以下操作:

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

namespace ConsoleApplication2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement root = doc.Root;
            XHierarchy xHierarchy = new XHierarchy();
            xHierarchy.Parse(root);
        }
        public class XHierarchy
        {
            public string Name { get; set; }
            public string Value { get; set; }
            public List<KeyValuePair<string, string>> Attributes { get; set; }
            public List<XHierarchy> Items { get; set; }

            public void Parse(XElement element)
            {
                Name = element.Name.LocalName;
                if (element.FirstNode != null)
                {
                    XmlNodeType type = element.FirstNode.NodeType;
                    if(type == XmlNodeType.Text) Value = element.FirstNode.ToString();
                }
                foreach(XAttribute attribute in element.Attributes())
                {
                    if (Attributes == null) Attributes = new List<KeyValuePair<string, string>>();
                    Attributes.Add(new KeyValuePair<string, string>(attribute.Name.LocalName, (string)attribute));
                }
                foreach(XElement child in element.Elements())
                {
                    if (Items == null) Items = new List<XHierarchy>();
                    XHierarchy childHierarchy = new XHierarchy();
                    Items.Add(childHierarchy);
                    childHierarchy.Parse(child);
                }

            }

        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.