使用XmlSerializer创建具有属性和值但不包含子元素的元素 [英] Using XmlSerializer to create an element with attributes and a value but no sub-element

查看:50
本文介绍了使用XmlSerializer创建具有属性和值但不包含子元素的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hopefully this should be an easy answer for someone out there (and possibly a dupe), but I can't seem to figure it out.

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

I need to output an element that looks like this:

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

我知道该如何获取:

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

数量类包含

public int qty;    
[XmlAttribute]
public string foo;

[XmlAttribute]
public string bar;

但随后,当然,无论我将数量插入多少变量都将成为其自己的子元素。

but then of course whatever variable I insert the quantity into becomes its own sub-element.

另一方面,如果我将数量作为父元素中的变量,则可以设置值并获取

On the other hand, if I make the Quantity a variable in the parent element, then I can set the value and get

<Quantity>37</Quantity>

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

but then I don't know how to get the attributes.

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

I would be very surprised if there weren't a simple way to do this with XmlSerializer, but I don't know it yet. Any ideas?

推荐答案

我在这里找到答案: Xmlserializer-控制元素-属性配对(已修订)

此处是操作方法:用 标记value属性[XmlText] 属性。

Here is how to do it: mark the value property with the [XmlText] attribute.

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;

}

这篇关于使用XmlSerializer创建具有属性和值但不包含子元素的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆