【问题标题】:Iterate through deserialized xml object遍历反序列化的 xml 对象
【发布时间】:2025-12-22 15:25:12
【问题描述】:

我有一个反序列化的 xml c# 对象。 我需要遍历 oject 以显示所有项目,在这种情况下只有一个项目,并显示每个项目的名称、颜色和大小。

xml:

<?xml version="1.0" encoding="utf-8"?>
<Catalog Name="Example">
  <Items>
    <Item Name="ExampleItem">
      <Colors>
        <Color Name="Black" Value="#000" />
        <Color Name="White" Value="#FFF" />
      </Colors>
      <Sizes>
        <Size Name="Small" Value="10"  />
        <Size Name="Medium" Value="20"  />
      </Sizes>
    </Item>
  </Items>
</Catalog>

xsd.exe 生成的类:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4927
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=2.0.50727.42.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Catalog {

    private CatalogItemsItem[][] itemsField;

    private string nameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlArrayItemAttribute("Item", typeof(CatalogItemsItem[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
    public CatalogItemsItem[][] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CatalogItemsItem {

    private CatalogItemsItemColorsColor[][] colorsField;

    private CatalogItemsItemSizesSize[][] sizesField;

    private string nameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlArrayItemAttribute("Color", typeof(CatalogItemsItemColorsColor[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
    public CatalogItemsItemColorsColor[][] Colors {
        get {
            return this.colorsField;
        }
        set {
            this.colorsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlArrayItemAttribute("Size", typeof(CatalogItemsItemSizesSize[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
    public CatalogItemsItemSizesSize[][] Sizes {
        get {
            return this.sizesField;
        }
        set {
            this.sizesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CatalogItemsItemColorsColor {

    private string nameField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CatalogItemsItemSizesSize {

    private string nameField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSet {

    private Catalog[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Catalog")]
    public Catalog[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

反序列化代码:

    System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Catalog));
            TextReader reader = new StreamReader("catalog.xml");
            Catalog catalog = (Catalog)xSerializer.Deserialize(reader);
            foreach (var item in catalog.Items)
            {


            }


   reader.Close();

当我通过代码设置时,catalog.items 中有一个项目,但它是空的,没有名称、颜色或尺寸。

任何想法我需要做什么?

谢谢

【问题讨论】:

    标签: .net xsd xml-deserialization


    【解决方案1】:

    XSD 并不完美 - 在这种情况下,它肯定会出错!

    就我而言,我有这样的代码:

    public partial class Catalog {
        private CatalogItemsItem[][] itemsField;
        private string nameField;
    
        /// <remarks/>
        [XmlArray(Form=XmlSchemaForm.Unqualified)]
        [XmlArrayItem("Item", typeof(CatalogItemsItem), 
         Form=XmlSchemaForm.Unqualified, IsNullable=false)]
        public CatalogItemsItem[][] Items {
            get {
    
    
    ......    
    
    public partial class CatalogItemsItem {
        private CatalogItemsItemColorsColor[][] colorsField;
        private CatalogItemsItemSizesSize[][] sizesField;
    

    那些“数组的数组”是您有时在使用 XSD 时遇到的典型错误。我什至无法反序列化您的测试 XML!

    一旦我把它改成简单的一维数组,一切都很好。

    public partial class Catalog {
        private CatalogItemsItem[] itemsField;
        private string nameField;
    
        /// <remarks/>
        [XmlArray(Form=XmlSchemaForm.Unqualified)]
        [XmlArrayItem("Item", typeof(CatalogItemsItem), 
         Form=XmlSchemaForm.Unqualified, IsNullable=false)]
        public CatalogItemsItem[] Items {
            get {
    
    
    ......    
    
    public partial class CatalogItemsItem {
        private CatalogItemsItemColorsColor[] colorsField;
        private CatalogItemsItemSizesSize[] sizesField;
    

    不,我很抱歉,我不知道有任何开关可以让您告诉 XSD 一直这样运行 - 它是手动的“生成后清理工作”,需要在这里完成。

    【讨论】:

      【解决方案2】:

      xsd.exe 生成了不正确的代码。你的课手工做起来并不难:

      public class Color
      {
          [XmlAttribute]
          public string Name;
      
          [XmlAttribute]
          public string Value;
      }
      
      public class Size
      {
          [XmlAttribute]
          public string Name;
      
          [XmlAttribute]
          public string Value;
      }
      
      public class Item
      {
          public Color[] Colors;
      
          public Size[] Sizes;
      }
      
      public class Catalog
      {
          [XmlAttribute]
          public string Name;
      
          public Item[] Items;
      }
      

      【讨论】:

      • 感谢您的回答。你是对的,但我提供的示例只是我想要做的简化版本。我只是想先掌握基础知识。我只是假设 xsd 生成的代码是正确的。
      • 轮到我证明,没有 xsd 编写这样的代码并不难 :)
      【解决方案3】:

      如果您不喜欢这种特殊的方法,并且您需要做的只是解析 xml,我强烈建议您使用 LINQ-to-xml 路线,它让我的生活变得更轻松。

      基础知识: http://msdn.microsoft.com/en-us/library/bb387087.aspx

      【讨论】: