简体   繁体   English

在 c# 中反序列化 xml 的最佳方法?

[英]best way to deserialize xml in c#?

I have following xml:我有以下 xml:

<return_obj from_call_to="categories">
  <categories>
    <category>
      <value>12341234</value>
      <label>First</label>
    </category>
    <category>
      <value>242234234</value>
      <label>Another</label>
    </category>
  </categories>
</return_obj>

so marked up an object to serialize this into所以标记了一个 object 将其序列化为

[XmlRoot(ElementName = "return_obj")]
public class returnobject
{
    [XmlElement]
    public category[] categories { get; set; }
}

public class category
{
    [XmlElement]
    public string value { get; set; }
    [XmlElement]
    public string label { get; set; }
}

and tried using this to do it并尝试使用它来做到这一点

    var ser = new XmlSerializer(typeof (returnobject));
    var obj = (returnobject)ser.Deserialize(File.OpenRead("test.xml"));

However, the categories collection always some ups null.但是,类别集合总是有些 ups null。

What am I doing wrong?我究竟做错了什么? Is there a better way?有没有更好的办法?

Thanks谢谢

Make categories field public in class returnobject .class returnobject中公开categories字段。 That would help.那会有所帮助。

XmlSerializer only looks at public fields and properties, so you have to make categories public in your returnobject class. XmlSerializer 只查看公共字段和属性,因此您必须在您的returnobject中公开categories

Also you have to specify the name of the XML array container you want to use, in your case categories - this worked for me:此外,您还必须在您的案例categories中指定要使用的 XML 数组容器的名称 - 这对我有用:

[XmlRoot(ElementName = "return_obj")]
public class returnobject
{
    [XmlArray("categories")]
    [XmlArrayItem("category")]
    public category[] categories { get; set; }
}

FYI, XmlSerializer has to generate type information of the serialization types.仅供参考,XmlSerializer 必须生成序列化类型的类型信息。 This can take a while, so you might find serialization and deserialization taking several hundred milliseconds.这可能需要一段时间,因此您可能会发现序列化和反序列化需要数百毫秒。 You can get around this by running SGEN to pre-generate the serialization assemblies.您可以通过运行 SGEN 来预生成序列化程序集来解决此问题。

Alternatively, you can use XmlReader to read the XML and just code the serialization yourself.或者,您可以使用 XmlReader 读取 XML 并自己编写序列化代码。 It's more code, but always performs well and isn't burdened with the extra assembly (generated or not).它的代码更多,但始终表现良好,并且没有额外的程序集(无论是否生成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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