我有这个XML:
<?xml version="1.0" encoding="UTF-8"?>
<doc>
<id>19</id>
<name>Name is here</name>
<note>leader-it test user</note>
<list name="products">
<elem>
<id>2537</id>
<name>Product #2537</name>
<status>Deleted</status>
<cost>1.00</cost>
</elem>
<elem>
<id>2541</id>
<name>Product #2541</name>
<status>Active</status>
<cost>1.00</cost>
</elem>
</list>
<list name="balance">
<elem>
<id>19</id>
<project>Project 15</project>
<balance>108046.1716</balance>
</elem>
</list>
<label />
<country>182</country>
</doc>
我试图反序列化
var account = XmlHelper.ParseXml<Account>(xml_string);
public static class XmlHelper
{
public class NamespaceIgnorantXmlTextReader : XmlTextReader
{
public NamespaceIgnorantXmlTextReader(TextReader reader) : base(reader) { }
public override string NamespaceURI
{
get { return String.Empty; }
}
}
public static T ParseXml<T>(string xml)
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
using (var xmlTextReader = new NamespaceIgnorantXmlTextReader(reader))
{
return (T)(serializer.Deserialize(xmlTextReader));
}
}
}
catch (Exception e)
{
return default(T);
}
}
}
使用这些类:
[XmlRoot(ElementName = "doc")]
public class Account
{
[XmlElement("id")]
public int Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("note")]
public string Note { get; set; }
[XmlArray("list")]
[XmlArrayItem(ElementName = "elem", Type = typeof(ProductListElement), IsNullable = false)]
public List<ProductListElement> Products { get; set; }
[XmlArray("list")]
[XmlArrayItem(ElementName = "elem", Type = typeof(BalanceListElement), IsNullable = false)]
public List<BalanceListElement> Balance { get; set; }
[XmlElement("label")]
public string Label { get; set; }
[XmlElement("country")]
public int CountryId { get; set; }
}
[Serializable]
public class ProductListElement
{
[XmlElement("id")]
public int ProductId { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("status")]
public string Status { get; set; }
[XmlElement("cost")]
public string Cost { get; set; }
}
[Serializable]
public class BalanceListElement
{
[XmlElement("id")]
public int BalanceId { get; set; }
[XmlElement("project")]
public string Project { get; set; }
[XmlElement("balance")]
public string Balance { get; set; }
}
我发现了这个错误:
XML元素&#39;列表&#39;来自命名空间&#39;&#39;已经出现在 目前的范围。使用XML属性指定另一个XML名称或 元素的命名空间。
如何使用XML属性指定另一个XML名称?
感谢。
答案 0 :(得分:-1)
您在课程中有两个属性,标签为&#39; elem&#39;。在这种情况下不需要使用数组。见下面的课程:
[XmlRoot(ElementName = "doc")]
public class Account
{
[XmlElement("id")]
public int Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("note")]
public string Note { get; set; }
[XmlElement(ElementName = "list")]
public List<BalanceListElement> Balance { get; set; }
[XmlElement("label")]
public string Label { get; set; }
[XmlElement("country")]
public int CountryId { get; set; }
}