【问题标题】:Understanding and using XSD理解和使用 XSD
【发布时间】:2014-05-10 09:28:02
【问题描述】:

假设我有一个像这样的 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>

我也是由 Visual Studio 类生成的,我想你明白我的意思,所以我不会发布代码(只有你会问它:))。

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

但我以这种方式收到错误。

我在这里得到NullReferenceException

newDC.other_properties.introduction_txt = "Lorem ipsum dolor sit amet";

我应该如何使用 generate-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");
            }


       }
}

统一更新: 生成的类

//------------------------------------------------------------------------------
// <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;
        }
    }
}

【问题讨论】:

  • 您是否从 XSD 创建了 .cs 类?为了将 xsd 用作对象并引用它的新实例,这必须先完成吗?
  • @Hexie 是的,ofc,我什至写过它>我也是由 Visual Studio 类生成的
  • 好的,那么您有一个包含 xsd 各个属性的 .cs 类文件?即您有一个名为 some_data 的属性,它是一个枚举?
  • @Hexie 是的,我更新了问题
  • 命名空间在哪里?无论如何,我会添加一个答案,您应该能够稍微调整以使您的解决方案发挥作用。 (PS - 您可能需要考虑使用通用工具将此 XSD 转换为一个类 - 如下所述) - 但是,它们的行为都相同,因此答案仍应为您提供所需的内容(答案基于 XSD使用 XSDGenerator.exe 转换)。

标签: c# asp.net xml xsd


【解决方案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");
    }

如果您随后需要序列化构建的对象(示例),那么您将在此之后进行,如果您需要课程或一些帮助,请告诉我。

我希望这会有所帮助?

【讨论】:

  • 表示代码有错误。出于某种原因,它在命名空间后需要},并表示没有{
  • 您是否更改了代码以引用您的 XSD 类?请记住,使用您的代码,您正在设置 other_properties 属性,但没有设置其他属性(即 person / person.some_data)(因为它们是必需的,代码将不会运行)
  • @DanilGholtsman 请使用您的确切 XSD 查看编辑后的帖子。现在应该可以 100% 工作了 - 请告诉我。
  • 它以System.ArgumentException: Non white space characters cannot be added to content. 失败
  • 好了,问题解决了,我就这样写pastebin.com/XwL3DQEs非常感谢!
猜你喜欢
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
相关资源
最近更新 更多