开发者

Is possible get a value from a XML and convert it?

I'm creating a program where I save information in a XML, in that XML I put the value and its type (DataType is an XML).

Is there a way to get that value in a object variable with its datatype? I'm having problems where the value is a string or decimal, integers, etc.

EXAMPLE:

<Answer ProblemID="0" ObjectiveID="1" IsCorrect="False">
  <Result DataType="System.Nullable`1[System.Decimal]" Value="45" />
</Answe开发者_运维百科r>
<Answer ProblemID="0" ObjectiveID="1" IsCorrect="False">
  <Result DataType="System.Nullable`1[System.Decimal]" Value="Null" />
</Answer>
<Answer ProblemID="0" ObjectiveID="5" IsCorrect="False">
  <Result DataType="System.Nullable`1[Factory.Factories.Comparison2.Comparators]" Value="Null" />
</Answer>


sounds like what you want is xml serialization, something like this:

// serialize an object to XML string
public string ToXml<_type>(_type itm)
{
    XmlSerializer ser = new XmlSerializer(itm.GetType());
    StringWriter sw = new StringWriter();
    ser.Serialize(sw, itm);
    return sw.ToString();
}

public _type FromXml<_type>(string str)
{
    XmlSerializer ser = new XmlSerializer(itm.GetType());
    return (_type)ser.Deserialize(new StringReader(xml));
}

edit

you can control how the object is serialized by using attributes on the items you want to serialize (or not):

public class Movie
{
   // Serialize the price field as an attribute with the given namspace
   [XmlAttribute( Namespace ="www.diranieh.com")]
   public decimal price;

   //serialize as <MovieName>
   [XmlElement("MovieName")]
   public string Title;

   // dont serialize this
   [XmlIgnore]
   public int Rating;

}

more information here on msdn


Well, if you have an object with string, decimal, int properties, you can Serialize the object to XML. I'm not sure if this is what you're looking for though...

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜