[英]ns1: C# deserialization issue
以下是用於獲取ns1:問題的測試代碼,我總是得到一個沒有任何內容的對象。
如果刪除兩個[XmlType]
和[XmlRoot]
則會出錯。
我確信可能已經有人遇到了可能找不到正確的搜索詞的問題,
完全希望這是一件簡單的事情。
[XmlType(AnonymousType = true, Namespace = "http://itaintworking.com/test/")]
[XmlRoot(Namespace = "http://itaintworking.com/test/", IsNullable = false)]
public class Clients
{
public string clientName { get; set; }
public addressDetails addressDetails { get; set; }
}
public class addressDetails
{
public int addressId { get; set; }
}
[Test(Description = "Serialization Exception")]
public void CheckDeserializer()
{
var strXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><ns1:Clients xmlns:ns1=\"http://itaintworking.com/test/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ><clientName>hello</clientName><addressDetails><addressId>98989</addressId></addressDetails></ns1:Clients>";
var x = XmlSerializer<Clients>.Deserialize(strXml);
Assert.IsNotNull(x);
}
我正在使用一些使用泛型的代碼,還有另一種方法默認為UTF8編碼,而xmlReaderSetting為null。
/// <summary>
/// Deserializes a XML string into an object
/// </summary>
/// <param name="xml">The XML string to deserialize</param>
/// <param name="encoding">The encoding</param>
/// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlReaderSettings"/></param>
/// <returns>An object of type <c>T</c></returns>
public static T Deserialize(string xml, Encoding encoding, XmlReaderSettings settings)
{
if (string.IsNullOrEmpty(xml))
throw new ArgumentException("XML cannot be null or empty", "xml");
var xmlSerializer = new XmlSerializer(typeof(T));
using (var memoryStream = new MemoryStream(encoding.GetBytes(xml)))
{
using (var xmlReader = XmlReader.Create(memoryStream, settings))
{
return (T)xmlSerializer.Deserialize(xmlReader);
}
}
}
目前尚不清楚您將如何解決此問題。
由於它目前矗立在XML中, clientName
和addressDetails
的內元素Clients
元素不在同一個命名空間。 因此,一種解決方法是:
[XmlType(AnonymousType = true, Namespace = "http://itaintworking.com/test/")]
[XmlRoot(Namespace = "http://itaintworking.com/test/", IsNullable = false)]
public class Clients
{
[XmlElement(Namespace="")]
public string clientName { get; set; }
[XmlElement(Namespace = "")]
public addressDetails addressDetails { get; set; }
}
另一個解決方法可能是更改XML中的名稱空間:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:Clients xmlns:ns1="http://itaintworking.com/test/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:clientName>hello</ns1:clientName>
<ns1:addressDetails>
<ns1:addressId>98989</ns1:addressId>
</ns1:addressDetails>
</ns1:Clients>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.