1

我有一个如下所示的 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.
}

问题在于映射节点 - 我宁愿获取它的属性集合,然后为每个属性创建一个字符串 - 我不完全确定如何解决这个问题 - 我尝试使用 XmlAnyAttribute 和 XmlArrayItem

干杯

4

1 回答 1

5

是的,你可以在这里使用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 - 缺少一个结束标签)

于 2013-08-14T12:59:16.327 回答