简体   繁体   English

如何在C#XML序列化中将属性添加到变量中?

[英]How can i add an attribute into a variable in c# xml serialization?

I am new to XML serialization in C#. 我是C#中XML序列化的新手。 I want to serialize my Dependency object instance so that it looks like this: 我想序列化我的Dependency对象实例,使其看起来像这样:

<Dependency Software="Some software">some value</Dependency>

I tried this: 我尝试了这个:

public class Dependency{
    [XmlAttribute("Software")]
    public string soft;
    public string value;
}

However, the output looks like the below which is not what I want: 但是,输出如下所示,这不是我想要的:

<Dependency Software="Some Software">
 <value>some value</value>
</Dependency>

Is there any way to achieve my desired output? 有什么办法可以达到我想要的输出?

A public property's value will appear in an element with the property name if you do not tell the serializer otherwise. 如果您不告诉序列化程序,则公共属性的值将出现在带有属性名称的元素中。

To get the output you want, you need to decorate it with the XmlText attribute, for example: 要获得所需的输出,您需要使用XmlText属性装饰它,例如:

public class Dependency
{
    [XmlAttribute("Software")]
    public string soft;
    [XmlText]
    public string value;
}

The property value will then appear as the value of the parent class element - Dependency in this case. 然后,该属性值将显示为父类元素的值-在这种情况下为Dependency

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

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