What is the best way to create an XML document that conforms to the XSD schema?

I have an XSD and I need to create an XML document to send to the clients of the company I work with. The documents I submit will be checked against this XSD scheme.

What is the best way to create an XML document that conforms to the XSD schema? I mean, I'm looking for best practices and the like. I am new to this and while "Googling" here and there, I have found people using XmlTextWriter, DataSet.WriteXml and others.

  • DataSet.WriteXml seems to me not very good. This is what I did:

    var ds = new DataSet();
    ds.ReadXmlSchema(schemaFile);
    ds.Tables["TableName"].Rows.Add("", "", 78, true, DateTime.Now);
    ...
    ds.WriteXml("C:\\xml.xml");
    

    I found that it generates a node with NewDataSet, and the nodes are not in the correct order.

  • XmlTextWriter, I find it a little longer ... but I will, if there is no other choice.

What do you think is the best way to do this? Are there any other approaches to this? I would put the circuit here if it weren’t so long, and if it was connected with the question.

+3
source share
4 answers

The main theme in .NET is the use of XML Serialization .

In your case, I would do the following:

  • run xsd.exe too .XSD to generate source code for classes (xsd / c)
  • create an application that uses these generated classes. Keep in mind that you can extend these classes using the "partial classes" technique.
  • in code, create an instance of XmlSerializer and serialize class instances.

Example:

Given this scheme:

<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Foo" nillable="true" type="Foo" />
  <xs:complexType name="Foo">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="Bar" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="Baz" type="UntypedArray" />
    </xs:sequence>
  </xs:complexType>


  <xs:complexType name="UntypedArray">
    <xs:choice minOccurs="1" maxOccurs="unbounded">
      <xs:element name="Type1" type="Type1"                 minOccurs="1" maxOccurs="1"/>
      <xs:any     namespace="##other" processContents="lax" minOccurs="1" maxOccurs="1"/>
    </xs:choice>
  </xs:complexType>


  <xs:complexType name="Type1" mixed="true">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="Child" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

xsd.exe :

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)]
public partial class Foo {

    private string barField;

    private object[] bazField;

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

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("", typeof(System.Xml.XmlElement), IsNullable=false)]
    [System.Xml.Serialization.XmlArrayItemAttribute(typeof(Type1), IsNullable=false)]
    public object[] Baz {
        get {
            return this.bazField;
        }
        set {
            this.bazField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class Type1 {

    private string childField;

    private string[] textField;

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

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

Foo , :

    Foo foo = new Foo();
    // ...populate foo here...
    var builder = new System.Text.StringBuilder();
    XmlSerializer s = new XmlSerializer(typeof(Foo));
    using ( var writer = System.Xml.XmlWriter.Create(builder))
    {
        s.Serialize(writer, foo, ns);
    }
    string rawXml = builder.ToString();

. , XmlWriters, , .

, XML, xml . :

    Foo foo = new Foo();
    // ...populate foo here...
    var builder = new System.Text.StringBuilder();
    var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };
    var ns = new XmlSerializerNamespaces();
    ns.Add("","");
    XmlSerializer s = new XmlSerializer(typeof(Foo));
    using ( var writer = System.Xml.XmlWriter.Create(builder, settings))
    {
        s.Serialize(writer, foo, ns);
    }
    string rawXml = builder.ToString();

XML- - XmlSerializer. Deserialize.

+6

.. http://msdn.microsoft.com/en-us/library/x6c1kb0s%28v=vs.110%29.aspx

csharp:

(programs- > visualStudio- > visualstudioTools- > VisualstudioCommandPrompt)

xsd , :

xsd /classes /fields /language:CS MyXSDSCHEMAFILE.xsd

( MyXSDSCHEMAFILE.xsd xsd)

cs , cs, , . , , , (classname - , cs):

classname myvariablename = new classname(); // so easy :)
// now you just fill with content
myvariablename.whatever.andever.field = "JaWerHatDasErfunden";// you just set a field

xml ( )

: , xsd .
, , Null Pointer.

+2

Source: https://habr.com/ru/post/1710803/


All Articles