我有一个如下所示的XML文件:
<Categories>
<Category Name="Mobile">
<SubCategory Name="Mobile Phones" MarkUp="1.2">
<Mapping Category1="COMMUNICATION" Category2="PHONE" Category3="MOBILE" Category4="MOBILE PHONE" Category5="ANDROID" Category6="" Category7="" />
<Mapping Category1="COMMUNICATION" Category2="PHONE" Category3="MOBILE" Category4="MOBILE PHONE" Category5="BLACKBERRY OS" Category6="" Category7="" />
<Mapping Category1="COMMUNICATION" Category2="PHONE" Category3="MOBILE" Category4="MOBILE PHONE" Category5="OTHER" Category6="" Category7="" />
<Mapping Category1="COMMUNICATION" Category2="PHONE" Category3="MOBILE" Category4="MOBILE PHONE" Category5="SYMBIAN" Category6="" Category7="" />
<Mapping Category1="COMMUNICATION" Category2="PHONE" Category3="MOBILE" Category4="MOBILE PHONE" Category5="WINDOWS PHONE" Category6="" Category7="" />
</SubCategory>
</Categories>
我目前正在反序列化:
[XmlRoot(ElementName = "Category")]
public class XmlCategory
{
[XmlAttribute(AttributeName = "Name")]
public string Name { get; set; }
[XmlElement("SubCategory")]
public XmlSubCategory[] XmlSubCategories { get; set; }
}
public class XmlSubCategory
{
[XmlAttribute(AttributeName = "Name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "MarkUp")]
public string MarkUp { get; set; }
[XmlElement("Mapping")]
public XmlMapping[] Mappings { get; set; }
}
public class XmlMapping
{
[XmlAttribute(AttributeName = "Category1")]
public string Category1 { get; set; }
// etc.
}
问题在于Mapping节点 - 我宁愿得到它的属性集合,然后为每个节点创建一个字符串 - 我不确定如何解决这个问题 - 我尝试过使用XmlAnyAttribute和XmlArrayItem < / p>
干杯
答案 0 :(得分:4)
是的,你可以在这里使用XmlAnyAttribute
,虽然我个人建议明确的成员方法是优越的,即你的
public class XmlMapping
{
[XmlAttribute] public string Category1 { get; set; }
[XmlAttribute] public string Category2 { get; set; }
[XmlAttribute] public string Category3 { get; set; }
[XmlAttribute] public string Category4 { get; set; }
[XmlAttribute] public string Category5 { get; set; }
[XmlAttribute] public string Category6 { get; set; }
[XmlAttribute] public string Category7 { get; set; }
}
然而,这也有效:
public class XmlMapping
{
[XmlAnyAttribute]
public XmlAttribute[] Attributes { get; set; }
}
然后只列举它:
foreach (var map in subCat.Mappings)
{
var attribs = map.Attributes;
if (attribs != null)
{
foreach (var attrib in attribs)
{
System.Console.WriteLine("{0}={1}", attrib.Name, attrib.Value);
}
}
}
对我来说很好......(虽然我必须修复破碎的xml - 缺少一个结束标记)