Generating Xml File Using Xsd File

Generating XML file using XSD file

Suppose we have Test.xsd file that looks like this:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyClass">
<xs:complexType>
<xs:sequence>
<xs:element name="Field1"
type="xs:string"/>
<xs:element name="Field2"
type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
  1. Create classes using xsd tool:

    xsd.exe /classes Test.xsd

    This will generate Test.cs file.

  2. Add Test.cs file to your solution.

  3. Create instance of MyClass, defined in XSD schema and XmlSerialize it:

    using System.Xml.Serialization;
    // ...
    var data = new MyClass { Field1 = "test1", Field2 = "test2" };
    var serializer = new XmlSerializer(typeof(MyClass));
    using (var stream = new StreamWriter("C:\\test.xml"))
    serializer.Serialize(stream, data);

Result:

<?xml version="1.0" encoding="utf-8"?>
<MyClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Field1>test1</Field1>
<Field2>test2</Field2>
</MyClass>

Generating XML file in C# using XSD file

You are missing some steps in your code to actually make the message. The generated cs file from your xsd has a class called list(). That is your start point when you want to create the complete xml structure.
Under list you have a repeating group called Sam, xsd.exe translated that into an array. Xsd.exe does not know lists. so the next thing you need to do is define the occurs that Sam will be in the xml file. And for eacht Sam there is an array called Analysis that also needs to be defined.
If you do this and then serialize the content to an xml file you will get what you want. But keep in mind that you need to fill all the elements in the classes. If you do not the serializer will take the default value, which is 0 for numeric fields and null for alphanumeric. an null value is not serialized so the element is left out making your xml content invalid.

the below example works but is missing a lot of elements

var list = new list();
list.Sam = new Sam[1];

var sample = new Sam { UploadCode = "test1", UploadId = "test2", Analyses = new Ana[1]};
var analysis = new Ana { Analysis = "Test2", Result = "123" };

sample.Analyses[0] = analysis;
list.Sam[0] = sample;

var serializer1 = new XmlSerializer(typeof(list));
using (var stream = new StreamWriter("test.xml"))
{
serializer1.Serialize(stream, list);
}

Generate XML file in C# with XSD file

I have found the answer :

  • I did not need to change my class generated by the xsd.exe

This is the code I ended with, it works perfectly now :

                foreach (Factuur huidigeFactuur2 in e.SelectedObjects)
{
XmlSerializer serializer2 = new XmlSerializer(typeof(KilometerUpload));
TextWriter writer = new StreamWriter(@"C:\test2.xml");

string chassisnummer = huidigeFactuur2.Wagen.Chassisnummer;
string kilometerstatus = huidigeFactuur2.KMStand.ToString();

KilometerUpload item = new KilometerUpload
{
KilometerRegistration = new KilometerUploadKilometerRegistration[] { new KilometerUploadKilometerRegistration{ ChassisNumber = chassisnummer , TypeOfData = "120", KilometerStatus = kilometerstatus} },
};

serializer2.Serialize(writer, item);

How to generate sample XML documents from their DTD or XSD?

I think Oxygen (http://www.oxygenxml.com/) does it as well, but that's another commerical product. It's a nice one, though... I'd strongly recommend it for anyone doing a lot of XML work. It comes in a nice Eclipse plugin, too.

I do believe there is a free, fully-featured 30 day trial.

generating xml based on xsd schema (with .NET)

Instead of using Program, you should use the class generated from the xsd. When I run

xsd /classes schema.xsd

It creates a schema.cs file. When I include this in my project, I can write this code:

class Program
{
public static void Main()
{
var data = new capType { tel = new[] {
new telType { source = "buffalo", time = 1 }
} };

var serializer = new XmlSerializer(typeof(capType));
using (var stream = new StreamWriter(@"E:\cap_test.xml"))
{
serializer.Serialize(stream, data);
}
}
}

Which writes:

<?xml version="1.0" encoding="utf-8"?>
<cap xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tel>
<time>1</time>
<source>buffalo</source>
</tel>
</cap>

The fact that the time property is of type double in schema.cs means that you can only input a valid number.

How to generate XML file from dataset using XSD and MVC

This gives exact results. Getting started is tough, the rest is easy.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Linq;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string FILENAME = @"c:\temp\test.xml";

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string identification =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<EN:eDWR" +
" xmlns:EN=\"urn:us:net:exchangenetwork\"" +
" xmlns:SDWIS=\"http://www.epa.gov/sdwis\"" +
" xmlns:ns3=\"http://www.epa.gov/xml\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
"/>";

XDocument doc = XDocument.Parse(identification);
XElement eDWR = doc.Elements().Where(x => x.Name.LocalName == "eDWR").FirstOrDefault();

XNamespace EN = eDWR.GetNamespaceOfPrefix("EN");
XNamespace SDWIS = eDWR.GetNamespaceOfPrefix("SDWIS");
XNamespace ns3 = eDWR.GetNamespaceOfPrefix("ns3");
XNamespace xsi = eDWR.GetNamespaceOfPrefix("xsi");

DataTable dt = QueryDataBase();

foreach (DataRow row in dt.AsEnumerable())
{
XElement submission = new XElement(EN + "Submission");
submission.Add(new object[] {
new XAttribute(EN + "submissionFileCreatedDate", row.Field<DateTime>("submissionFileCreatedDate")),
new XAttribute(EN + "submissionFileName", row.Field<string>("submissionFileName")),
new XAttribute(EN + "submissionID", row.Field<int>("submissionID"))
});

eDWR.Add(submission);

XElement LabAccreditation = new XElement(EN + "LabIdentification", new object[] {
new XElement(EN + "LabAccreditationIdentifier", row.Field<string>("LabAccreditationIdentifier")),
new XElement(EN + "LabAccreditationAuthorityName", row.Field<string>("LabAccreditationAuthorityName"))
});

XElement labReport = new XElement(EN + "LabReport");
XElement labIdentification = new XElement(EN + "LabIdentification");
submission.Add(labReport);
labReport.Add(labIdentification);
labIdentification.Add(LabAccreditation);

XElement sampleIdentification = new XElement(EN + "SampleIdentification", new object[] {
new XElement(EN + "LabSampleIdentifier", row.Field<int>("LabSampleIdentifier")),
new XElement(EN + "PWSIdentifier", row.Field<string>("PWSIdentifier")),
new XElement(EN + "PWSFacilityIdentifier", row.Field<string>("PWSFacilityIdentifier")),
new XElement(EN + "SampleRuleCode", row.Field<string>("SampleRuleCode")),
new XElement(EN + "SampleMonitoringTypeCode", row.Field<string>("SampleMonitoringTypeCode"))
});

XElement sample = new XElement(EN + "Sample");
labReport.Add(sample);
XElement RecordID = new XElement(SDWIS + "RecordID", row.Field<int>("RecordID"));
sample.Add(RecordID);
sample.Add(sampleIdentification);

}

doc.Save(FILENAME);

}
public DataTable QueryDataBase()
{
DataTable dt = new DataTable();

//Here is an example of getting a datatable from a database
string SQL = "Enter Your SQL Here";
string connStr = "Enter your database connection string here";

//uncomment instructions below
//SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
//adapter.Fill(dt);

//I will build a dummy datatable for your test case
dt.Columns.Add("submissionFileCreatedDate", typeof(DateTime));
dt.Columns.Add("submissionFileName", typeof(string));
dt.Columns.Add("submissionID", typeof(int));
dt.Columns.Add("LabAccreditationIdentifier", typeof(string));
dt.Columns.Add("LabAccreditationAuthorityName", typeof(string));
dt.Columns.Add("RecordID", typeof(int));
dt.Columns.Add("LabSampleIdentifier", typeof(int));
dt.Columns.Add("PWSIdentifier", typeof(string));
dt.Columns.Add("PWSFacilityIdentifier", typeof(string));
dt.Columns.Add("SampleRuleCode", typeof(string));
dt.Columns.Add("SampleMonitoringTypeCode", typeof(string));

dt.Rows.Add(new object[] {
DateTime.Parse("2012-07-21"),
"B_14271BJB.csv",
1,
"OR100024",
"STATE",
155628,
123321,
"OR4100237",
"DIST-A",
"TC",
"RP"
});

return dt;
}

}
}

How to generate XML data from XSD using Java?

After digging in a little bit, realised the environment variable value for XMLBEANS_LIB is wrongly set. The XMLBEANS_LIB expects to be pointed to the lib directory of the XML Beans distribution not to xmlbeans-3.1.0.jar. So the correct value for that is

 export XMLBEANS_LIB=/home/user/Programs/xmlbeans-3.1.0/lib

I was able to generate the XMLInstance (as a String) using XSD ( given as String) using the below code.

import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.xsd2inst.SampleXmlUtil;
import org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator;

import java.util.ArrayList;
import java.util.List;

public class XmlInstanceGeneratorImpl {
private static final Logger logger = LogManager.getLogger(XmlInstanceGeneratorImpl.class);

/**
* Specifies if network downloads are enabled for imports and includes.
* Default value is {@code false}
*/
private static final boolean ENABLE_NETWORK_DOWNLOADS = false;

/**
* disable particle valid (restriction) rule
* Default value is {@code false}
*/
private static final boolean NO_PVR = false;

/**
* disable unique particle attribution rule.
* Default value is {@code false}
*/
private static final boolean NO_UPA = false;

public String generateXmlInstance(String xsdAsString, String elementToGenerate){
return generateXmlInstance(xsdAsString, elementToGenerate, ENABLE_NETWORK_DOWNLOADS, NO_PVR, NO_UPA);
}

public String generateXmlInstance(String xsAsString, String elementToGenerate, boolean enableDownloads,
boolean noPvr, boolean noUpa){
List<XmlObject> schemaXmlObjects = new ArrayList<>();
try {
schemaXmlObjects.add(XmlObject.Factory.parse(xsAsString));
} catch (XmlException e) {
logger.error("Error Occured while Parsing Schema",e);
}
XmlObject[] xmlObjects = schemaXmlObjects.toArray(new XmlObject[1]);
SchemaInstanceGenerator.Xsd2InstOptions options = new SchemaInstanceGenerator.Xsd2InstOptions();
options.setNetworkDownloads(enableDownloads);
options.setNopvr(noPvr);
options.setNoupa(noUpa);
return xsd2inst(xmlObjects, elementToGenerate, options);
}

private String xsd2inst(XmlObject[] schemas, String rootName, SchemaInstanceGenerator.Xsd2InstOptions options){
SchemaTypeSystem schemaTypeSystem = null;
if (schemas.length > 0) {
XmlOptions compileOptions = new XmlOptions();
if (options.isNetworkDownloads())
compileOptions.setCompileDownloadUrls();
if (options.isNopvr())
compileOptions.setCompileNoPvrRule();
if (options.isNoupa())
compileOptions.setCompileNoUpaRule();
try {
schemaTypeSystem = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions);
} catch (XmlException e) {
logger.error("Error occurred while compiling XSD",e);
}
}
if (schemaTypeSystem == null) {
throw new RuntimeException("No Schemas to process.");
}

SchemaType[] globalElements = schemaTypeSystem.documentTypes();
SchemaType elem = null;
for (SchemaType globalElement : globalElements) {
if (rootName.equals(globalElement.getDocumentElementName().getLocalPart())) {
elem = globalElement;
break;
}
}
if (elem == null) {
throw new RuntimeException("Could not find a global element with name \"" + rootName + "\"");
}
// Now generate it and return the result
return SampleXmlUtil.createSampleForType(elem);
}
}



Related Topics



Leave a reply



Submit