1

I have an XML string like this:

<foo>
  ...
  <barlist id="10">
    <bar ... />
    <bar ... />
    etc..
  </barlist>
</foo>

How do I get the id of barlist in deserializing it to an object?

My current code for doing this without serializing/deserializing the ID is this:

class FooData{
  [XmlArray("barlist")]
  [XmlArrayItem("bar",typeof(BarData))]
  public List<BarData> Bars;
}
2

1 Answer 1

2

Try add XmlAtribute to id object.

UPDATE: I'am adding example how you can deserialize it...

Classes:

[XmlType(AnonymousType=true)]
[XmlRoot(Namespace="", IsNullable=false)]
public class foo {
    [XmlElement("barlist")]
    public List<fooBarlist> barlist { get; set; }
}

[XmlType(AnonymousType=true)]
public class fooBarlist {
    [XmlElement("bar")]
    public List<fooBarlistBar> bar { get; set; }
    [XmlAttribute()]
    public byte id { get; set; }
}

[XmlType(AnonymousType=true)]
public class fooBarlistBar {
    [XmlAttribute()]
    public byte number { get; set; }
    [XmlAttribute()]
    public string value { get; set; }
}

test xml:

<foo>
 <barlist id="1">
  <bar number="1" value="Hi" />
  <bar number="2" value="Hello" />
  </barlist>
  <barlist id="2">
  <bar number="3" value="Bye" />
  <bar number="4" value="Bye bye" />
  </barlist>
</foo>

and the code to deserialize xml to object:

XmlSerializer serializer = new XmlSerializer(typeof(foo));
XmlReader reader = XmlReader.Create("D:\\test.xml");
foo testObj = serialier.Deserialize(reader) as foo;

and then we have result

result

Sign up to request clarification or add additional context in comments.

6 Comments

-1: no, that wouldn't work, even if it were spelled correctly.
@John Saunders: I updated my answer and added test example - it works for me.
Why do you have Attribute at the end of all the names? You know you can leave that off right?
so, your point is, if he want to change his classes, then he can do it?
I just tryed to show how it can be done thats it. I may be wrong, my answer can be useless to user, but its suggestion.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.