28

うまくいけば、これはそこにいる誰か(そしておそらくだまされた人)にとって簡単な答えになるはずですが、私はそれを理解できないようです.

次のような要素を出力する必要があります。

<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>37</Quantity>

しかし、属性を取得する方法がわかりません。

XmlSerializer でこれを行う簡単な方法がなかったら非常に驚くでしょうが、まだわかりません。何か案は?

4

1 に答える 1

57

ここで答えを見つけます: Xmlserializer - Control Element-Attribute Pairing (revised)

方法は次のとおりです: value プロパティを[XmlText]属性でマークします。

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;

}
于 2010-08-19T17:07:30.330 に答える