2012-03-28 9 views
0

モデル:XmlDeserialization:xmlconverterためのポイント

[XmlRoot(ElementName = "location", IsNullable = true)] 
public class location 
{ 
    public string city { get; set; } 
    public string country { get; set; } 
    public string street { get; set; } 
    public string postalcode { get; set; } 
    [XmlElement(ElementName = "geo:point")] 
    public geoLocation geo { get; set; } 
} 

[XmlRoot(ElementName = "geo:point", Namespace="http://www.w3.org/2003/01/geo/wgs84_pos#")] 
public class geoLocation 
{ 
    [XmlElement(ElementName = "geo:lat", Namespace="http://www.w3.org/2003/01/geo/wgs84_pos#")] 
    public string lat { get; set; } 
    [XmlElement(ElementName = "geo:long", Namespace = "http://www.w3.org/2003/01/geo/wgs84_pos#")] 
    public string lon { get; set; } 
} 

のxml:

<location> 
<city>Moscow</city> 
<country>Russian Federation</country> 
<street></street> 
<postalcode>236000</postalcode> 
<geo:point> 
<geo:lat>54.727483</geo:lat> 
<geo:long>20.501132</geo:long> 
</geo:point> 
</location> 

場所はOKですが、地理 - ではありません。私は何をすべきか? 私は名前空間を消去しようとしたとXmlElement属性定義の一部として、何の変化locationクラスのgeoLocationタイプの

+0

地理と間違っている何 - 何を見て期待しましたか? –

答えて

1

ここでは2つの問題があります。 1つは、Peter Aron Zentaiの言葉通り、プロパティレベルで名前空間を適用する必要があるということです。 XmlRootは、それがルートオブジェクト(あなたの場合は場所です)に置かれている場合にのみ効果があります。

第2の問題点は、要素名にプレフィックスを含めることによって、実際には "geo:point"という要素があることです。あなたは、 "geo"という接頭辞を持つ "http://www.w3.org/2003/01/geo/wgs84_pos#"という名前空間に、 "point"という名前の要素があることを言います。

最初の問題を解決するには - 名前空間指定子をXmlRootからプロパティ自体に移動するだけです。第二の修正要素名からプレフィックスを削除し、「GEO」の接頭辞で、シリアライザに正しく名前空間を設定するには:

[XmlRoot(ElementName = "location", IsNullable = true)] 
public class location 
{ 
    public string city { get; set; } 
    public string country { get; set; } 
    public string street { get; set; } 
    public string postalcode { get; set; } 
    [XmlElement(ElementName = "point", Namespace = "http://www.w3.org/2003/01/geo/wgs84_pos#")] 
    public geoLocation geo { get; set; } 
} 

public class geoLocation 
{ 
    [XmlElement(ElementName = "lat", Namespace = "http://www.w3.org/2003/01/geo/wgs84_pos#")] 
    public string lat { get; set; } 
    [XmlElement(ElementName = "long", Namespace = "http://www.w3.org/2003/01/geo/wgs84_pos#")] 
    public string lon { get; set; } 
} 

var serializer = new XmlSerializer(typeof (location)); 
var namespace = new XmlQualifiedName("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#"); 
var namespaces = new XmlSerializerNamespaces(new [] { namespace }); 
serializer.Serialize(myOutputStreamOrWriter, location, namespaces); 
0

置きXML名前空間はありません。この場合のXmlRootは適用されません!

[XmlRoot(ElementName = "location", IsNullable = true)] 
public class location 
{ 
    public string city { get; set; } 
    public string country { get; set; } 
    public string street { get; set; } 
    public string postalcode { get; set; } 
    [XmlElement(ElementName = "point", Namespace="http://www.w3.org/2003/01/geo/wgs84_pos#")] 
    public geoLocation geo { get; set; } 
} 
関連する問題