开发者

deserialise xml response into custom class

I am trying to deserialize the following xml structure into an object...

<?xml version="1.0" encoding="utf-8"?>
<xmlRoot>
    <nest1>
        <element1>A</element1>
        <nest2>
            <element2>aqbc</element2>
            <element3>vjd</element3>
        </nest2>
    </nest1>
</xmlRoot>

There is no schema for it and i cannot alter it. now i am getting problems with putting this structure into class form....

Tthe only information i am interested in is the values of the elements inside nest2. My C# class looks like the following...

/// <summary>
/// Summary description for FirstResponse
/// </summary>
[Serializable]
[System.Xml.Serialization.XmlRoot("nest2")]
public class FirstResponse
{
    [System.Xml.Serialization.XmlElement("element2")]
    public string Element2{ get; set; }

    [System.Xml.Serialization.XmlElement("element3")]
    public string Element3{ get; set; }
}

Using the code below, I receive an exception or I just get a empty Object...

FirstResponse response = null;

    try
    {
        XmlSerializer serializer = new XmlSerializer(typeof(FirstResponse));
        StringReader reader = new StringReader(xmlString);

        response = (FirstResponse)serializer.Deserialize(reader);
        reader.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    return response;

If i set the XmlRoot to 'nest2' i receive the exception; ' was not expected.'. If i change that value to 'xmlRoot' i get an empty object...

I am really not sure where i have gon开发者_JAVA技巧e wrong here....


Two step process:

  1. take your XML and run xsd.exe (found in c:\Program Files\Microsoft SDKs\Windows\v7.0a\Bin - or c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0a\Bin on a x64 OS) on it:

    xsd.exe yourfile.xml
    

    This results in a XML schema file yourfile.xsd

  2. take that XSD file and run xsd.exe on it again, the the /c option:

    xsd.exe /c yourfile.xsd
    

    This results in a C# file yourfile.cs which represents a 1:1 mapping of your XML file structure into a C# class, which you should be able to use to deserialize that XML file into a C# object

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜