2010-08-19 64 views
19

希望这应该是一个简单的答案(可能是一个愚蠢的),但我似乎无法弄清楚。使用XmlSerializer创建一个带有属性和值但没有子元素的元素

我需要输出看起来像这样的一个元素:

<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; 

但随后一个数量级当然无论我插入数量的变量变成它自己的子元素。

在另一方面,如果我做了一个数量可变的父元素,那么我可以设置的值,并得到

<Quantity>37</Quantity> 

但我不知道怎么弄的属性。

如果没有简单的方法来使用XmlSerializer来做这件事,我会感到非常惊讶,但我还不知道。有任何想法吗?

+0

的可能重复的[XmlSerializer的 - 控制元素-属性配对(修订)](http://stackoverflow.com/questions/732314/xmlserializer-control-element-attribute-pairing-revised) – 2010-08-19 17:11:02

回答

47

我在这里找到答案: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; 

} 
+0

1为与我的搜索相匹配的标题:) – 2013-04-22 07:10:32

+0

你回答了你自己的问题以及我的问题。 – Brandin 2013-07-03 19:58:54

+0

XmlText的解释并没有说明它适合于非文本值 – user3791372 2017-02-09 20:16:24

相关问题