-2

My goal is to get List<String> of <AccessKey>'s from XML string. How onw would parse such XML?

    <Project>
        <AccessKeys>
            <AccessKey>key_1</AccessKey>
            <AccessKey>key_2</AccessKey>
        </AccessKeys>
    </Project>

I've tried

[XmlArray("AccessKeys"), XmlArrayItem(typeof(AccessKeyData), ElementName = "AccessKey")]
public List<AccessKeyData> AccessKeys = new List<AccessKeyData>();

    [Serializable]
    public class AccessKeyData
    {
        public string AccessKey;
    }

I have no problem to get back single <AccessKey> When i have more <AccessKey> i get back empty lists/arrays.

BitRate
  • 1
  • 1
  • 5
    Do you definitely need to use XML serialization at all? I'd just use: `var keys = XDocument.Load(...).Descendants("AccessKey").Select(element => element.Value).ToList()` or similar. – Jon Skeet May 30 '22 at 13:27
  • Assuming your `AccessKeys` property belongs to some `Project` class, use `[XmlArray("AccessKeys"), XmlArrayItem("AccessKey")] public public List AccessKeys { get; set; }` as shown in [this answer](https://stackoverflow.com/a/1208702) by [Brian Ensink](https://stackoverflow.com/users/1254/brian-ensink) to [How to deserialize into a List using the XmlSerializer](https://stackoverflow.com/q/1208643). Demo here:https://dotnetfiddle.net/l5JQK6. I'd propose to close this as a duplicate, agree? Or do you require the extra `AccessKeyData` class? – dbc May 30 '22 at 14:05
  • I agree with @dbc that this looks like a duplicate of the linked answer from Brian Ensink, unless you specifically need an array of that class to be populated somewhere instead of a list of strings. I would think it should be easy enough, assuming you can get the list of strings, to concatenate them into whatever form you would like. Maybe add a `List AccessKeyList` that gets set, and then make AccessKey a property to concatenate those into a single string? If you really want arrays of classes you could just make a method or function to do that. – shelleybutterfly May 30 '22 at 14:58
  • @JonSkeet No, I do not need that. And it looks like it does the trick. I just wasn't aware of XDocument class. – BitRate May 31 '22 at 10:53
  • @dbc It looks like a duplicate. Thank you for your reply. – BitRate May 31 '22 at 10:59
  • 1
    @shelleybutterfly At this point List works for me, than you! – BitRate May 31 '22 at 11:00

1 Answers1

0

Please try the following solution.

c#

void Main()
{
    XDocument xdoc = XDocument.Parse(@"<Project>
        <AccessKeys>
            <AccessKey>key_1</AccessKey>
            <AccessKey>key_2</AccessKey>
        </AccessKeys>
    </Project>");

    List<String> listOfString = xdoc.Descendants("AccessKey")
      .Select(x => x.Value).ToList();

    Console.Write(listOfString);
}
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21