了解和使用XSD

时间:2014-03-31 06:26:12

标签: c# asp.net xml xsd

假设我有一个像这样的xsd文件

   <!-- <?xml version="1.0" encoding="utf-8"?>
    <xs:schema...  scheme and etc here--> 
      <xs:element name="data_container" >
        <xs:complexType>
          <xs:sequence>

            <xs:element name="people">
              <xs:complexType>
                <xs:sequence>

                  <xs:element name="person"  maxOccurs="unbounded">

                    <xs:complexType>
                      <xs:sequence>

                        <xs:element name="some_data">
                          <xs:complexType>
                            <xs:simpleContent>
                              <xs:extension base="xs:string">
                                <xs:attribute name="sx" use="required" >
                                  <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                      <xs:enumeration value="M"/>
                                      <xs:enumeration value="F"/>
                                    </xs:restriction>
                                  </xs:simpleType>
                                </xs:attribute>
                              </xs:extension>
                            </xs:simpleContent>
                          </xs:complexType>
                        </xs:element>

                      </xs:sequence>
                      <xs:attribute name="p_id" type="xs:ID" use="required" />
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
              </xs:complexType>
            </xs:element>

            <xs:element name="other_properties">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="introduction_txt"  type="xs:string"/>
                  <xs:element name="introduction_pic"  type="xs:string"/>
                </xs:sequence>
              </xs:complexType>
            </xs:element>

          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>

我也是由视觉工作室课程生成的,我想你明白我的意思所以我不会发布代码(只有你会询问它:))。

所以我尝试创建xml这样的文件(我以为我在这里找到了解决方案所以我用它作为例子How can I build XML in C#?,第二个答案)

但我这样得到错误。

我在这里得到NullReferenceException

  

newDC.other_properties.introduction_txt =&#34; Lorem ipsum dolor sit   阿梅特&#34 ;;

如何使用generated-from-xsd类帮助正确写入xml文件?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;
    using System.Text;

    namespace xsdTests
    {
        class Program
        {
            static void Main(string[] args)
            {
                xmlGenTest();
            }

            static void xmlGenTest()
            {
                XDocument doc = new XDocument();
                data_container newDC = new data_container();
                newDC.other_properties.introduction_txt = "Lorem ipsum dolor sit amet";

                doc.Add(newDC);

                doc.Save("C:\\temp\\data.xml");
            }


       }
}

UPD: 生成的类

//------------------------------------------------------------------------------
// <auto-generated>
//     Этот код создан программой.
//     Исполняемая версия:4.0.30319.18408
//
//     Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
//     повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// Этот исходный код был создан с помощью xsd, версия=4.0.30319.17929.
// 


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

    private data_containerPerson[] peopleField;

    private data_containerOther_properties other_propertiesField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("person", IsNullable=false)]
    public data_containerPerson[] people {
        get {
            return this.peopleField;
        }
        set {
            this.peopleField = value;
        }
    }

    /// <remarks/>
    public data_containerOther_properties other_properties {
        get {
            return this.other_propertiesField;
        }
        set {
            this.other_propertiesField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/XMLSchema.xsd")]
public partial class data_containerPerson {

    private data_containerPersonSome_data some_dataField;

    private string p_idField;

    /// <remarks/>
    public data_containerPersonSome_data some_data {
        get {
            return this.some_dataField;
        }
        set {
            this.some_dataField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute(DataType="ID")]
    public string p_id {
        get {
            return this.p_idField;
        }
        set {
            this.p_idField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/XMLSchema.xsd")]
public partial class data_containerPersonSome_data {

    private data_containerPersonSome_dataSX sxField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public data_containerPersonSome_dataSX sx {
        get {
            return this.sxField;
        }
        set {
            this.sxField = value;
        }
    }

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

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/XMLSchema.xsd")]
public enum data_containerPersonSome_dataSX {

    /// <remarks/>
    M,

    /// <remarks/>
    F,
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/XMLSchema.xsd")]
public partial class data_containerOther_properties {

    private string introduction_txtField;

    private string introduction_picField;

    /// <remarks/>
    public string introduction_txt {
        get {
            return this.introduction_txtField;
        }
        set {
            this.introduction_txtField = value;
        }
    }

    /// <remarks/>
    public string introduction_pic {
        get {
            return this.introduction_picField;
        }
        set {
            this.introduction_picField = value;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您已经将XSD转换为可用类(使用XSD.exe / XSDGenerator.exe)并且已在项目中包含该新类文件,那么您只需引用该类/创建它的新实例在使用它之前。 (在序列化之前,如果需要的话)。

修改

按如下方式更改xmlGenTest方法:

static void XmlGenTest()
    {
        var doc = new XDocument();

        var x = new data_container();
        x.other_properties = new data_containerOther_properties { introduction_pic = "a", introduction_txt = "b" };

        x.people = new data_containerPerson[1];
        x.people[0] = new data_containerPerson
            {
                p_id = "",
                some_data = new data_containerPersonSome_data { sx = data_containerPersonSome_dataSX.F }
            };

        doc.Add(x);

        doc.Save("C:\\temp\\data.xml");
    }

如果您需要序列化构建的对象(示例),那么您可以在此之后执行此操作,如果您需要课程或帮助,请告诉我。

我希望这有帮助吗?