【问题标题】:Using XmlSerializer to create an element with attributes and a value but no sub-element使用 XmlSerializer 创建具有属性和值但没有子元素的元素
【发布时间】:2010-08-19 17:01:41
【问题描述】:

希望这对外面的人(可能是骗子)来说应该是一个简单的答案,但我似乎无法弄清楚。

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

<Quantity foo="AB" bar="CD">37</Quantity>

我知道如何得到这个:

  <Quantity foo="AB" bar="CD">
    <qty>37</qty>
  </Quantity>

Quantity 类包含

public int qty;    
[XmlAttribute]
public string foo;

[XmlAttribute]
public string bar;

但是当然,我将数量插入的任何变量都会成为它自己的子元素。

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

<Quantity>37</Quantity>

但是我不知道如何获取属性。

如果没有使用 XmlSerializer 的简单方法来执行此操作,我会感到非常惊讶,但我还不知道。有什么想法吗?

【问题讨论】:

标签: c# xmlserializer


【解决方案1】:

我在这里找到答案:Xmlserializer - Control Element-Attribute Pairing (revised)

操作方法如下:用[XmlText] 属性标记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 仅适用于非复杂类型。我尝试装饰 object 类型并遇到运行时错误。
  • @user3791372 你的意思是像 CDATA 吗?
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 2021-10-06
  • 2023-03-23
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2013-07-03
  • 2014-07-06
相关资源
最近更新 更多