[英]Serialize XML into CSharp class
I have a xml string in a json data field. 我在json数据字段中有一个xml字符串。 I want to extract that value and compare that to the database's value for that field. 我想提取该值并将其与该字段的数据库值进行比较。
I used xsd.exe to generate the class for that xml (saw from here ). 我使用xsd.exe生成了该xml的类(从此处看到)。 I am using that class to deserialize the xml response. 我正在使用该类反序列化xml响应。 Then i used the method from here
to deserialize. 然后我从here
使用该方法反序列化。
I used 我用了
`XmlSerializer serializer1 = new XmlSerializer(typeof(class_gen_from_xml))
In the below code, I extracted the xml source from the json response and then did as below: 在下面的代码中,我从json响应中提取了xml源,然后执行了以下操作:
string xmlSource = "<ResultSet><Result precision=\"address\"> <Latitude>47.643727</Latitude></Result></ResultSet>";
XmlSerializer serializer = new XmlSerializer(typeof(ResultSet));
ResultSet output;
using (StringReader reader = new StringReader(xmlSource))
{
output = (ResultSet)serializer.Deserialize(reader);
}
` And I am getting an Exception and debugging reveals nothing at all. `而且我得到了一个异常,调试一点也没有发现。 Is there something I am missing in the code ? 代码中有我缺少的东西吗?
Probably something wrong with your ResultSet
class, this works fine for me: 您的ResultSet
类可能有问题,对我来说很好用:
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class ResultSet
{
private ResultSetResult[] resultField;
[System.Xml.Serialization.XmlElementAttribute("Result")]
public ResultSetResult[] Result
{
get
{
return this.resultField;
}
set
{
this.resultField = value;
}
}
}
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResultSetResult
{
private decimal latitudeField;
private string precisionField;
public decimal Latitude
{
get
{
return this.latitudeField;
}
set
{
this.latitudeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string precision
{
get
{
return this.precisionField;
}
set
{
this.precisionField = value;
}
}
}
With your de-serialization code: 使用反序列化代码:
static void Main(string[] args)
{
string xmlSource = "<ResultSet><Result precision=\"address\"> <Latitude>47.643727</Latitude></Result></ResultSet>";
XmlSerializer serializer = new XmlSerializer(typeof(ResultSet));
ResultSet output;
using (StringReader reader = new StringReader(xmlSource))
{
output = (ResultSet)serializer.Deserialize(reader);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.