简体   繁体   English

c#:将未知的xml元素反序列化为数组或列表

[英]c#: deserialize unknown xml elements to an array or list

Given the following XML: 给出以下XML:

<browser>
    <firefox company="mozilla"></firefox>
    <chrome company="google"></chrome>
    <ie company="microsoft"></ie>     
</browser>

This is my code for deserializing: 这是我反序列化的代码:

[XmlRoot("browser")]
public class Browser
{
    //--List or Array
    List<BrowserType> browserTypes {get; set;}
}

public class BrowserType
{
    [XmlAttribute("company")]
    public string company {get; set;}
}

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Browser));
StreamReader sr = new StreamReader("browser.xml");
Browser browser = (Browser )xmlSerializer.Deserialize(sr);

foreach(var item in browserTypes)
{
    //--List browser types 
}

For this problem, I cannot do the following code for the XmlArrayItem since I do not know the element name. 对于这个问题,我不能为XmlArrayItem执行以下代码,因为我不知道元素名称。

[XmlArray("browser")]
[XmlArrayItem("firefox")]
public BrowserType[] BrowserTypes{ get; set; }

How to deserialize unknown xml elements to an array or list? 如何将未知的xml元素反序列化为数组或列表?

Update 更新

Ok, so using xml serialization, you can specify a list of BrowserType s and then specify the XmlElement name and type for each of the derived types. 好的,所以使用xml序列化,您可以指定BrowserType的列表,然后为每个派生类型指定XmlElement名称和类型。 Example: 例:

[XmlRoot("browser")]
public class Browser
{
    private readonly List<BrowserType> _items = new List<BrowserType>();
    [XmlElement("firefox", typeof(Firefox))]
    [XmlElement("chrome", typeof(Chrome))]
    [XmlElement("ie", typeof(IE))]
    public List<BrowserType> Items { get { return _items; } }
}

public class BrowserType
{
    [XmlAttribute("company")]
    public string Company { get; set; }
}

public class Firefox : BrowserType
{
}

public class Chrome : BrowserType
{
}


public class IE : BrowserType
{
}

Original Entry: 原始条目:

If you can switch to XDocument instead, then you could grab all the descendants of the root node and then get the name of each descendant. 如果可以改用XDocument ,则可以获取根节点的所有后代,然后获取每个后代的名称。 Example: 例:

    static void Main(string[] args)
    {
        string xmlString = @"<browser>
<firefox company=""mozilla""></firefox>
<chrome company=""google""></chrome>
<ie company=""microsoft""></ie>     
</browser>";

        XDocument xdoc = XDocument.Parse(xmlString);
        var elementNames = xdoc.Root.Descendants()      // Get the descendants of the root node
                                    .Select(element => element.Name.LocalName);     // Project each XElement to its name
        string[] browserTypes = elementNames.ToArray();

        foreach (string browserType in browserTypes)
        {
            Console.WriteLine(browserType);
        }
    }

Output: 输出:

firefox
chrome
ie

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

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