C# 使用XmlSerializer创建具有属性和值但没有子元素的元素

C# 使用XmlSerializer创建具有属性和值但没有子元素的元素,c#,xmlserializer,C#,Xmlserializer,希望这对某些人来说应该是一个简单的答案(可能是个傻瓜),但我似乎无法理解 我需要输出一个如下所示的元素: <Quantity foo="AB" bar="CD">37</Quantity> 当然,我插入数量的任何变量都会变成它自己的子元素 另一方面,如果我将数量设置为父元素中的变量,那么我可以设置该值并获得 <Quantity>37</Quantity> 37 但是我不知道如何获得属性 如果没有一种简单的方法来使用XmlSerializer实

希望这对某些人来说应该是一个简单的答案(可能是个傻瓜),但我似乎无法理解

我需要输出一个如下所示的元素:

<Quantity foo="AB" bar="CD">37</Quantity>
当然,我插入数量的任何变量都会变成它自己的子元素

另一方面,如果我将数量设置为父元素中的变量,那么我可以设置该值并获得

<Quantity>37</Quantity>
37
但是我不知道如何获得属性

如果没有一种简单的方法来使用XmlSerializer实现这一点,我会非常惊讶,但我还不知道。有什么想法吗?

我在这里找到了答案:

下面是如何做的:用属性标记value属性

public class Quantity {
  // your attributes
  [XmlAttribute]
  public string foo;

  [XmlAttribute]
  public string bar;

  // and the element value (without a child element)
  [XmlText]
  public int qty;

}

很遗憾,对XmlText的解释没有说明它适用于非文本值。请注意
XmlText
仅适用于非复杂类型。我试图装饰一个
对象
类型,但出现了运行时错误。@user3791372你是说喜欢CDATA吗?
<Quantity>37</Quantity>
public class Quantity {
  // your attributes
  [XmlAttribute]
  public string foo;

  [XmlAttribute]
  public string bar;

  // and the element value (without a child element)
  [XmlText]
  public int qty;

}