【问题标题】:Represent XML without xsd表示没有 xsd 的 XML
【发布时间】:2010-02-02 14:53:15
【问题描述】:

注意:我不能使用 XSD...不打算详细说明原因。

我在一个应该反序列化的类中正确表示以下 xml 时遇到问题:

XML:

<product>
   <sku>oursku</sku>
   <attribute name="attrib1">value1</attribute>
   <attribute name="attrib2">value2</attribute>
   <attribute name="attribx">valuex</attribute>
</product>

问题在于表示属性节点

到目前为止我所拥有的是:

[XmlElement(ElementName = "Attribute")]
public Attribute[] productAttributes;

public class Attribute
{
    [XmlAttribute(AttributeName = "Name")]
    public string attributeName;

    public Attribute()
    {

    }
}

我知道我缺少一些东西来存储价值,也许

【问题讨论】:

    标签: .net xml serialization xmlserializer


    【解决方案1】:

    在您的 XML 上运行 xsd.exe 两次以创建中间 XSD,然后从中创建一个 C# 类会产生以下结果:

    [Serializable]
    [XmlType(AnonymousType=true)]
    [XmlRoot(Namespace="", IsNullable=false)]
    public partial class product 
    {
        private string skuField;
        private productAttribute[] attributeField;
    
        [XmlElement(Form=XmlSchemaForm.Unqualified)]
        public string sku {
            get {
                return this.skuField;
            }
            set {
                this.skuField = value;
            }
        }
    
        [XmlElement("attribute", Form=XmlSchemaForm.Unqualified, IsNullable=true)]
        public productAttribute[] attribute {
            get {
                return this.attributeField;
            }
            set {
                this.attributeField = value;
            }
        }
    }
    
    [Serializable]
    [XmlType(AnonymousType=true)]
    public partial class productAttribute {
    
        private string nameField;
        private string valueField;
    
        [XmlAttribute]
        public string name {
            get {
                return this.nameField;
            }
            set {
                this.nameField = value;
            }
        }
    
        [XmlText]
        public string Value {
            get {
                return this.valueField;
            }
            set {
                this.valueField = value;
            }
        }
    }
    

    这对你有用吗?

    【讨论】:

      【解决方案2】:

      您尝试生成的 XML 看起来不像 XmlSerializer 能够本地创建的那种。我认为您将不得不实现 IXmlSerializable 并自定义编写它。

      【讨论】:

        【解决方案3】:

        我认为你需要使用属性[XmlText]

        public class Attribute
        {
            [XmlAttribute(AttributeName = "Name")]
            public string attributeName;
        
            [XmlText]
            public string Value {get;set;}
        
            public Attribute()
            {
        
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-25
          • 2011-08-16
          • 1970-01-01
          • 1970-01-01
          • 2011-02-28
          • 1970-01-01
          • 2021-01-14
          • 1970-01-01
          相关资源
          最近更新 更多