سؤال

this might be a silly noobish question, but please bear with me =)

In my program I receive a piece of xml something akin to this:

<markers>
        <marker id="35" name="Test1" address="anyway123" type="event"/>
        <marker id="370" name="Test2" address="" type="event"/>
        <marker id="251" name="Test3" address="somewhere 1337" type="com"/>
</markers>

What I want to know if there's a way to have a class, containing sort of something like this:

private int id;
private string name;
private string address;
private string type;

public int Id {
    get {
        return id;
    }
    set {
        id = value;
    }
}
public string Name {
    get {
        return name;
    }
    set {
        name = value;
    }
}
public string Address {
    get {
        return address;
    }
    set {
        address = value;
    }
}
public string Type {
    get {
        return type;
    }
    set {
        type = value;
    }
}

Lets call it "EventClass" and then simply go like:

Could I then simply go something like this: List eventList = "XMLStuff"

And if yes, what would XML stuff entail? xD

Regards, -Logan =)

هل كانت مفيدة؟

المحلول

You can use the standard XmlSerializer if you're willing to make a few modifications to your class:

  • XML is case-sensitive so you should use lower-case names for your properties (id, name, etc.
  • create a containing class with an array of your data class
  • Add the attribute [XmlRoot("markers")] to the containing class
  • Add the attribute [XmlElement("marker")] to the array property

Something like this:

[XmlRoot("markers")]
public class EventList
{
    [XmlElement("marker")]
    public List<EventClass> EventClasses {get; set;}
}


public class EventClass
{
    public int id {get; set;}
    public string name {get; set;}
    public string address {get; set;}
    public string type {get; set;}
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top