问题描述
我有一些麻烦与我的XML字符串的反序列化到我的对象。我没有得到任何错误,但值不填充(价值不空
他们只是,
)。我看着那个有同样的问题的一些问题,但这些问题通常包括人不具有 [XmlRoot]
或 [的XmlElement]
定义。
下面是一个有点我的XML字符串:
字符串的xmlString = @<结果>< dpv_answer值=Y/><拉链值=95118-4007/>< /结果>
下面是deseralize功能:
StandardAddress地址=新StandardAddress();使用
(XmlReader中读取= XmlReader.Create(新StringReader(XML)))
{
试
{
地址=(StandardAddress)新的XmlSerializer (typeof运算(StandardAddress))反序列化(阅读器)。
}
赶上(InvalidOperationException异常X)
{
//字符串传递不是XML,简单地返回defaultXmlClass
}
}
返回地址;
下面是一个有点对象声明:
[XmlRoot(结果)]
公共类StandardAddress
{
[的XmlElement(的ElementName =dpv_answer)]
公共字符串dpv_answer {搞定;组; }
[的XmlElement(的ElementName =拉链)]
公共字符串拉链{搞定;组; }
}
dpv_answer
和拉链
是复杂的元素不只是一个字符串。请尝试以下操作:
[XmlRoot(结果)]
公共类StandardAddress
{
[的XmlElement(的ElementName =dpv_answer)]
公共dpv_answer dpv_answer {搞定;组; }
[的XmlElement(的ElementName =拉链)]
公共拉链拉链{搞定;组; }
}
公共类dpv_answer
{
[XmlAttribute(值)]
公共字符串值{获得;组; }
}
公共类拉链
{
[XmlAttribute(值)]
公共字符串值{获得;组; }
}
I am having some troubles with the deserialization of my xml string to my object. I am not getting any errors but the values aren't populating (the values aren't null
they are just ""
). I've looked at a few questions that had the same issue but those problems usually consisted of people not having the [XmlRoot]
or [XmlElement]
defined.
Here is a bit of my xml string:
string xmlString = @"<results><dpv_answer value=""Y"" /><zip value=""95118-4007"" /></results>"
Here is the function to deseralize:
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;
Here is a bit of the object declaration:
[XmlRoot("results")]
public class StandardAddress
{
[XmlElement(ElementName = "dpv_answer")]
public string dpv_answer { get; set; }
[XmlElement(ElementName = "zip")]
public string zip { get; set; }
}
dpv_answer
and zip
are complex elements not just a string. Try the following:
[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; }
}
这篇关于XML反序列化在C#中的复杂元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!