简体   繁体   中英

XML Deserialize and return part of the object as XML

Dont know even how to search for this, but when I deserialize an xml string, I want it to return the first level of the XML:

String: <pkt><cmd>logreq</cmd><data><name>scott</name><password>abc123</password><designator>R233</designator><token>123456</token></data></pkt>

When I use this code:

    class xmlFunctions
{
    public Cmd GetCmd(string sXML)
    {
        Cmd cmd = new Cmd();
        try
        {
            var sr = new StringReader(sXML);
            var xs = new XmlSerializer(typeof(Cmd));
            cmd = (Cmd)xs.Deserialize(sr);
            return cmd;
        }
        catch (Exception)
        {                
           Console.WriteLine("Cannot Parse Input.");
        }
        return cmd;
    }
}

and this is my Cmd object:

[XmlRoot("pkt")]
public class Cmd
{
    public string cmd { get; set; }
    public string data { get; set; }

}

I would expect that Cmd.cmd = logreq and Cmd.data = <name>scott</name><password>abc123</password><designator>R233</designator><token>123456</token>

but the data = scott.

How do I get it to return the XML part above? it seems that it wants to deserialize all the xml and not just the first level?

Thanks.

I think you really mean Parse a XML string and return the root node. In that case this is what you're looking for How to Parse XML with XmlReader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM