使用对象参数反序列化XML

时间:2019-01-24 08:49:19

标签: c# xml deserialization

我有一个简单的xml,只是无法反序列化到一个对象,我的模型类有问题。我刚刚收到一个空物体。

"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
\n<response>
\n<lst name=\"responseHeader\">
   <int name=\"status\">0</int>
   <int name=\"QTime\">20596</int>
</lst>\n
</response>\n"

我这样序列化:

var x = result.Content;     
XmlSerializer serializer = new XmlSerializer(typeof(response));              
StringReader rdr = new StringReader(x);
response resultingMessage = 
(response)serializer.Deserialize(rdr);

我的模型类如下:

[XmlType("response")]
public class response
{
    [XmlElement("responseHeader")]
    public string Name { get; set; }
    public List<lst> Lst { get; set; }
}

public class lst
{
    [XmlElement("name")]
    public string Name { get; set; }
    [XmlElement("int")]
    public List<Int> Int { get; set; }
}

public class Int
{
    [XmlElement("status")]
    public int status { get; set; }
    [XmlElement("QTime")]
    public int QTime { get; set; }
}

2 个答案:

答案 0 :(得分:2)

结合一些需要纠正的东西。

您需要清洁Xml

XmlSerializer serializer = new XmlSerializer(typeof(response));              
StringReader rdr = new StringReader(xmlString.Replace(@"\n",String.Empty).Replace(@"\'","'"));
response resultingMessage = 
(response)serializer.Deserialize(rdr);

第二,您的数据结构需要进行一些更改。例如,响应不需要name。它必须是lst的一部分。而且它是attribute,而不是element。因此需要用[XmlAttribute]

装饰
[XmlType("response")]
public class response
{
    [XmlElement("lst")]
    public List<lst> Lst { get; set; }
}

public class lst
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("int")]
    public List<Int> Int { get; set; }
}

public class Int
{
    [XmlAttribute(AttributeName="name")]
    public string Name { get; set; }
    [XmlText]
    public string Text { get; set; }
}

输出

enter image description here

答案 1 :(得分:0)

尝试这样,

/*
var x = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n<lst name=\"responseHeader\"><int name=\"status\">0</int><int name=\"QTime\">20596</int></lst>\n</response>\n";

*/

var x = result.Content;   
 x= x.Replace("\\n", string.Empty).Replace("\\", string.Empty);  
XmlSerializer serializer = new XmlSerializer(typeof(response));              
StringReader rdr = new StringReader(x);
response resultingMessage = 
(response)serializer.Deserialize(rdr);

有时多余的字符可能会导致转换问题。