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>
位置还可以,但是地理 - 不是。我该怎么办? 我试图删除命名空间,但没有变化
答案 0 :(得分:1)
这里有两个问题。正如Peter Aron Zentai所提到的那样,您需要在属性级别应用命名空间。 XmlRoot
只有在根对象(在您的情况下是位置)上才有效。
第二个问题是,通过在元素名称中包含前缀,实际上是说你有一个名为“geo:point”的元素。您应该说的是在名称空间“http://www.w3.org/2003/01/geo/wgs84_pos#”中有一个名为“point”的元素,其前缀为“geo”。
要纠正第一个问题 - 只需将名称空间说明符从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);
答案 1 :(得分:0)
将geoLocation
类的XML命名空间放在location
类中,作为XmlElement
属性定义的一部分。在这种情况下,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; }
}