希望这对外面的人(也可能是骗子)来说应该是一个简单的答案,但我似乎无法弄明白。
我需要输出一个如下所示的元素:
<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 执行此操作的简单方法,我会感到非常惊讶,但我还不知道。有什么想法吗?
最佳答案
我在这里找到答案: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;
}
关于c# - 使用 XmlSerializer 创建具有属性和值但没有子元素的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3524224/