0

Lets say I got an xsd file like this one

   <!-- <?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>

Also I got generated by visual studio class, I guess you understand what do I mean so I wouldn't posting the code (only if yo will ask about it :)).

So I trying to create xml file like that (I thought that I found solution here so I used it as an example How can I build XML in C#?, second answer)

but I getting errors this way.

I get NullReferenceException here

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

How I should properly write into xml file with generated-from-xsd class help?

    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: generated class

//------------------------------------------------------------------------------
// <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;
        }
    }
}
Community
  • 1
  • 1
DanilGholtsman
  • 2,354
  • 4
  • 38
  • 69
  • Have you created the .cs class from the XSD? In order to use the xsd as an object and reference a new instance of it, this would have to be done first? – Hexie Mar 31 '14 at 06:41
  • @Hexie yes, ofc, I even wrote about it >Also I got generated by visual studio class – DanilGholtsman Mar 31 '14 at 06:42
  • Ok, so you have a .cs class file that contains the individual properties of the xsd? i.e. you have a property called some_data which is an Enum? – Hexie Mar 31 '14 at 06:44
  • Where is the namespace? Regardless, I will add an answer that you should be able to adjust slightly to get your solution to work. (PS - you might want to consider using the general tools to convert this XSD To a class - mentioned below) - however, they all behave the same, so the answer should still give you what you need (the answer is based on a XSD converted using XSDGenerator.exe). – Hexie Mar 31 '14 at 06:50
  • @Hexie well, actually I don't think that there problem with namespaces because when I declare `data_container ` variable or others its see it – DanilGholtsman Mar 31 '14 at 06:58

1 Answers1

1

If you have already converted the XSD to a usable class (using XSD.exe / XSDGenerator.exe) and you have included that new class file in your project, then you would merely reference the class / create a new instance of it, prior to working with it. (Before serializing it back, if needed).

EDIT

Change your xmlGenTest method as follows:

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");
    }

If you then need to serialize the built object (example), then you would do it after this, if you need a class or some help with that, please let me know.

I hope this helps?

Hexie
  • 3,955
  • 6
  • 32
  • 55
  • it says that there are errors in the code. For some reason it requires `}` after namespace and says that there are no `{` – DanilGholtsman Mar 31 '14 at 07:14
  • Have you changed to code to reference your XSD class? Remember, with your code you have, you are setting the other_properties property, but have not set the others (i.e. person / person.some_data) without these set (as they are required, the code will not run) – Hexie Mar 31 '14 at 07:19
  • @DanilGholtsman Please see the Edited post, using your exact XSD. This should now work 100% - please let me know. – Hexie Mar 31 '14 at 07:56
  • it fails with `System.ArgumentException: Non white space characters cannot be added to content.` – DanilGholtsman Apr 01 '14 at 03:02
  • well, the problem solved, I just write like this http://pastebin.com/XwL3DQEs thank you very much! – DanilGholtsman Apr 01 '14 at 03:55