This question already has answers here:
How to Deserialize XML document
                                
                                    (17个答案)
                                
                        
                                6年前关闭。
            
                    
我在将xml字符串反序列化为对象时遇到一些麻烦。我没有收到任何错误,但是没有填充值(这些值不是null而是"")。我看过几个有相同问题的问题,但这些问题通常由未定义[XmlRoot][XmlElement]的人员组成。

这是我的xml字符串:

string xmlString = @"<results><dpv_answer value=""Y"" /><zip value=""95118-4007"" /></results>"


这是反序列化的函数:

StandardAddress address = new StandardAddress();

using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    try
    {
        address = (StandardAddress)new XmlSerializer(typeof(StandardAddress)).Deserialize(reader);
    }
    catch (InvalidOperationException x)
    {
        // String passed is not XML, simply return defaultXmlClass
    }
}

return address;


这是一些对象声明:

[XmlRoot("results")]
public class StandardAddress
{
    [XmlElement(ElementName = "dpv_answer")]
    public string dpv_answer { get; set; }
    [XmlElement(ElementName = "zip")]
    public string zip { get; set; }
}

最佳答案

dpv_answerzip是复杂的元素,而不仅仅是字符串。请尝试以下操作:

[XmlRoot("results")]
public class StandardAddress
{
    [XmlElement(ElementName = "dpv_answer")]
    public dpv_answer dpv_answer { get; set; }

    [XmlElement(ElementName = "zip")]
    public zip zip { get; set; }
}

public class dpv_answer
{
    [XmlAttribute("value")]
    public string Value { get; set; }
}


public class zip
{
    [XmlAttribute("value")]
    public string Value { get; set; }
}

关于c# - Xml反序列化与C#中的复杂元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18409954/

10-13 07:07