简体   繁体   English

XmlSerializer反序列化空元素的属性

[英]XmlSerializer deserialize attribute of empty elements

I have a problem with my XmlSerializer. 我的XmlSerializer有问题。 I try to deserialize this file : 我尝试反序列化此文件:

<MyClass Id="12">
    <ProblemHere Value="8"/>
    <OtherElement>0</OtherElement>
    <fdp>NTM</fdp>
</MyClass>

in this class : 在这一节课中:

[XmlType(TypeName = "MyClass")]
public class MyClass
{
    [XmlAttribute(AttributeName = "Id")]
    public int Id { get; set; }

    //Here I try somes head but it's a failure
    public int ProblemHere { get; set; }

    public int OtherElement{ get; set; }

    public string fdp{get; set}
}

As you may understand, what I want is to set ProblemHere to its value (8 here). 如您所知,我想要将ProblemHere设置为其值(此处为8)。 Is there any simple way to do that or do I have to create a ProblemHere class with an int Value property (seems like an overkill to me) ? 有什么简单的方法可以做到这一点,还是我必须创建一个具有int Value属性的ProblemHere类(对我来说似乎ProblemHere过头了)?

As far as I know you have to create a separate class. 据我所知,您必须创建一个单独的类。 The property is named "ProblemHere", but you want the attribute to be named "value" - I do not know of any attributes in .Net that can do this. 该属性被命名为“ ProblemHere”,但是您希望该属性被命名为“ value”-我不知道.Net中的任何属性都可以做到这一点。

I usually prefer to have visual studio generate a base XSD (which I can tweak later), and then use xsd.exe to generate a set of (de)serialization classes for it. 我通常更喜欢让Visual Studio生成基本的XSD(稍后可以进行调整),然后使用xsd.exe为其生成一组(反序列化)类。

Yes, you have to create a class to represent that aspec of the data, ie 是的,您必须创建一个类来表示该数据规范,即

public class Foo {
    [XmlAttribute]
    public int Value {get;set;}
}

public Foo ProblemHere { get; set; }

That is the only way XmlSerializer will work with the structure you want. 这是XmlSerializer使用所需结构的唯一方法。

you could do something like this 你可以做这样的事情

private int _problem = 0;
public int ProblemHere { get {return _problem; }  set { _problem = value; } }

not pretty but works 不漂亮但是可以用

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

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