0
我有下面的XML作爲例子:在C#MVC命名空間或結腸反序列化XML節點
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:api="http://www.sample.com/api">
<entry>
<existing>true</existing>
<api:object category="user" id="100">
<api:last-name>Smith</api:last-name>
<api:first-name>John</api:first-name>
</api:object>
</entry>
<entry>
<existing>false</existing>
<api:object category="user" id="101">
<api:last-name>Smith</api:last-name>
<api:first-name>Bob</api:first-name>
</api:object>
</entry>
</feed>
現在我嘗試反序列化的XML,並能順利拿到價值爲節點< 現有的>。問題是我得到的節點內的數據的空值爲< api:>前綴。我讀過這與名稱空間有關,但我無法使它工作我正在使用C#MVC。
我的模型如下:
ElementsUsersRoot.cs
[Serializable]
[XmlType(Namespace = "http://www.w3.org/2005/Atom")]
[XmlRoot(ElementName = "feed", Namespace = "http://www.w3.org/2005/Atom", IsNullable = false)]
public class ElementsUsersRoot
{
public ElementsUsersRoot()
{
ElementsUsersDetails = new List<ElementsUsersData>();
}
[XmlElement("entry")]
public List<ElementsUsersData> ElementsUsersDetails { get; set; }
ElementsUsersData.cs
[Serializable]
[XmlRoot("entry")]
public class ElementsUsersData
{
[XmlElement("existing")]
public bool IsExisting { get; set; }
[XmlElement("api:object")]
public ElementsUsersAttributes UserAttributes { get; set; }
}
ElementsUsersAttributes.cs
0下面[Serializable]
[XmlRoot("api:object", Namespace = "http://www.sample.com/api")]
public class ElementsUsersAttributes
{
[XmlElement("api:first-name")]
public string Fname { get; set; }
[XmlElement("api:last-name")]
public string Lname{ get; set; }
}
代碼:
using (var client = new HttpClient())
{
var byteArray = Encoding.ASCII.GetBytes(apiAccount + ":" + apiPassword);
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
var stream = await client.GetStreamAsync(apiEndpoint);
var serializer = new XmlSerializer(typeof(ElementsUsersRoot));
ElementsUsersRoot userXmlData = (ElementsUsersRoot)serializer.Deserialize(stream);
//Add cache here
return userXmlData;
}
前綴*不*一個名字的「一部分」。例如。你從'http:// www.sample.com/api'命名空間獲得了名爲'object'的元素。在XML中,'api'用來表示名稱空間的事實是*無意義的*。 –