SQLite create DB table from xml (xsd) - c#

I have xml (xsd) file. I need create db table in SQLite db, and load data from XML to this table (in C# application).
I try to use this code:
string ConnectionStr = "Data Source=mydb.sqlite;Version=3; New=True; Compress = True;";
NDbUnit.Core.INDbUnitTest Database = new NDbUnit.Core.SqlLite.SqlLiteDbUnitTest(ConnectionStr);
Database.ReadXmlSchema("AS_ACTSTAT.xsd");
Database.ReadXml("AS_ACTSTAT.xml");
Database.PerformDbOperation(NDbUnit.Core.DbOperationFlag.CleanInsertIdentity);
But I have this error (read xml schema):
SqlDbCommandBuilder.CreateSelectCommand(DataSet, string) failed for
tableName = 'ActualStatus'
Schema file:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:sch="http://purl.oclc.org/dsdl/schematron" xmlns:usch="http://www.unisoftware.ru/schematron-extensions" xmlns:sql="urn:schemas-microsoft-com:mapping-schema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="ActualStatuses" sql:is-constant="true" >
<xs:annotation>
<xs:documentation>sostav</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="ActualStatus" maxOccurs="unbounded" sql:relation="AS_ACTSTAT">
<xs:annotation>
<xs:documentation>status</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attribute name="ACTSTATID" use="required">
<xs:annotation>
<xs:documentation>key</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:totalDigits value="10"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="NAME" use="required">
<xs:annotation>
<xs:documentation>name
0 – non actual
1 – actual
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="100"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
ps Also I try use SqlXml 4.0 from Microsoft (it works great with MS SQL 2008), but can't find OLEDB driver for SQLite.
Any idea? I need something like SqlXml 4.0 fo SQlite, because i dont know structure of xml file previously.

Related

Why my xml file is detected as a valid xml?

I wanted to find a xsd file for MS office Docx's [Content_Types].xml file (Where can I find the XSDs of DOCX XML files?)
I got an answer, but I've found that for some reason this xsd cause all of my xml files to pass validation test
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<Export_toLab Sending_Site="3">
<Tracker Tracker_ID="55" Booklet_Type="3">
<Booklet Booklet_ID="542"/>
</Tracker>
</Export_toLab>
This is the xsd file (schema of MS office Docx's [Content_Types].xml):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xs:schema xmlns="http://schemas.openxmlformats.org/package/2006/content-types"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://schemas.openxmlformats.org/package/2006/content-types"
elementFormDefault="qualified" attributeFormDefault="unqualified" blockDefault="#all">
<xs:element name="Types" type="CT_Types"/>
<xs:element name="Default" type="CT_Default"/>
<xs:element name="Override" type="CT_Override"/>
<xs:complexType name="CT_Types">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="Default"/>
<xs:element ref="Override"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="CT_Default">
<xs:attribute name="Extension" type="ST_Extension" use="required"/>
<xs:attribute name="ContentType" type="ST_ContentType" use="required"/>
</xs:complexType>
<xs:complexType name="CT_Override">
<xs:attribute name="ContentType" type="ST_ContentType" use="required"/>
<xs:attribute name="PartName" type="xs:anyURI" use="required"/>
</xs:complexType>
<xs:simpleType name="ST_ContentType">
<xs:restriction base="xs:string">
<xs:pattern
value="(((([\p{IsBasicLatin}-[\p{Cc}\(\)<>#,;:\\"/\[\]\?=\{\}\s\t]])+))/((([\p{IsBasicLatin}-[\p{Cc}\(\)<>#,;:\\"/\[\]\?=\{\}\s\t]])+))((\s+)*;(\s+)*(((([\p{IsBasicLatin}-[\p{Cc}\(\)<>#,;:\\"/\[\]\?=\{\}\s\t]])+))=((([\p{IsBasicLatin}-[\p{Cc}\(\)<>#,;:\\"/\[\]\?=\{\}\s\t]])+)|("(([\p{IsLatin-1Supplement}\p{IsBasicLatin}-[\p{Cc}"\n\r]]|(\s+))|(\\[\p{IsBasicLatin}]))*"))))*)"
/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ST_Extension">
<xs:restriction base="xs:string">
<xs:pattern
value="([!$&'\(\)\*\+,:=]|(%[0-9a-fA-F][0-9a-fA-F])|[:#]|[a-zA-Z0-9\-_~])+"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
This is the validation code:
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("http://schemas.openxmlformats.org/package/2006/content-types", "opc-contentTypes.xsd");
XDocument doc = XDocument.Load("MyFile.xml");
string msg = "";
doc.Validate(schemas, (o, e) => {msg += e.Message + Environment.NewLine;});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
Why the xml file is deteced as a valid xml?
Thanks
I think you may have the same issue as here:
XDocument.Validate is always successful
To summarise, the validate method does not raise an error for the nodes it does not know about. You should simply check before validating that the namespace of the xml is the same as the schema - if not its definitely a fail so no need to validate.

DataSet XML Response from Web Service consumption

Below is the valid and updated XML I was trying to consume:
<DataSet xmlns="http://tempuri.org/">
<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
<xs:element name="response">
<xs:complexType>
<xs:sequence>
<xs:element name="user" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="status" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="code" type="xs:string"/>
<xs:attribute name="value" type="xs:string"/>
<xs:attribute name="description" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="error" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="code" type="xs:string"/>
<xs:attribute name="message" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="operation" type="xs:string"/>
<xs:attribute name="timestamp" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element ref="response"/>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<response diffgr:id="response1" msdata:rowOrder="0" diffgr:hasChanges="inserted" operation="AUTHENTICATION" timestamp="2015-11-19 18:21:17.457" msdata:hiddenresponse_Id="0">
<user diffgr:id="user1" msdata:rowOrder="0" diffgr:hasChanges="inserted" id="blumaesnetwork" msdata:hiddenresponse_Id="0"/>
<status diffgr:id="status1" msdata:rowOrder="0" diffgr:hasChanges="inserted" code="315" value="FAILED" description="Authentication Failed. User ID Not Found" msdata:hiddenresponse_Id="0"/>
<error diffgr:id="error1" msdata:rowOrder="0" diffgr:hasChanges="inserted" code="-1" message="User Not Found" msdata:hiddenresponse_Id="0"/>
</response>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
With the C# code below:
x.LoadXml(_xmlString);
XDocument x1 = new XDocument();
x1 = XDocument.Parse(_xmlString);
IEnumerable<responseStatus> ListRsts = (from e in x1.Descendants("responseStatus")
select new responseStatus
{
code = e.Element("code").Value,
value = e.Element("value").Value,
description = e.Element("description").Value
});
foreach (var br in ListRsts)
codeField = (br.code);
It keeps throwing error that i missed "diffgr".
What you get as a respsone XML is a saved DataSet. Instead of trying to decipher the diffgram it generates you better leverage the ReadXml method of that type. It is fully equipped to read the xml and gives you specified behavior on the Tables and Relationships.
var ds = new DataSet();
ds.ReadXml(File.Open(#"C:\temp\ds.xml", FileMode.Open));
var listOfStatus = from row in ds.Tables["response"].Rows.Cast<DataRow>()
from status in row.GetChildRows("response_status")
select new { code = status["code"],
value = status["value"],
description = status["description"] };
foreach(var stat in listOfStatus)
{
// do what ever you need to do with the Status record(s)
}
In the above code I read the rows in the table response and then fetch the childrows for the table status. For every status row an anonymous type is created with the three fields you seem to be interested in. You can process those by iterating over the IEnumerable of that anonymous type.

Can't get xs:element with attribute

I have XML elements with and without attributes
<xs:element name='element0'>
<xs:complexType name='internationalShoeSize'>
<xs:annotation>
<xs:documentation>Data ...</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:simpleContent>
<xs:extension base='xs:string'>
<xs:attribute name='attribute0' type='xs:string' />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name='element1'>
<xs:complexType name='internationalShoeSize'>
<xs:annotation>
<xs:documentation>Data1 ...</xs:documentation>
</xs:annotation>
</xs:element>
When I get the elements in a DataTable, only get the elements without attributes.
foreach(DataColum colum in table.colums)
{
....
}
This foreach only get the elements without attributes: the element1.
How can I get all the elements, with and without attributes?
I think you need to start with a better schema snippet, the one you've posted is mangled beyond use. I took yours and cleaned it up - in the process maybe deviated from your intentions; feel free to take my sample and used it to edit your question for better illustration.
(Alternatively, if you have a sample XML, post that instead - it might be even easier to explain.)
<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="element0" type="internationalShoeSize"/>
<xs:element name="element1" type="internationalShoeSize"/>
<xs:complexType name="internationalShoeSize">
<xs:annotation>
<xs:documentation>Data ...</xs:documentation>
</xs:annotation>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="attribute0" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>
Meanwhile, this is the equivalent data structure you would get (on .NET):
Your attribute is there...

Deserialize a XML fragment to class that has been generated by xsd.exe

I have a xml file that I want to read it and then interpret and convert to respective classes that were generated from xsd tool. Here are the steps which I am trying:
I created a XSD file.
Converted the respective xsd file into respective set of classes.
I made some xml files through same set of classes (from step 2) and xmlserializer.
Now I am reading back from those xml files and I wan't to convert it into classes (generated from step2)
I am pasting the code I have worked till now, I seem to get an exception when I am deserializing, {"There is an error in XML document (0, 0)."}
var doc = XDocument.Load(filePath);
var query2 = from b in doc.Root.Descendants()
select b;
foreach (var item in query2)
{
switch (item.Name.LocalName)
{
case "SomeStringValue":
XmlSerializer srz = new XmlSerializer(typeof(SomeClassGeneratedfromXSD));
var writer=item.CreateReader();
parameterFromFile.SomeProperty = (SomeClassGeneratedfromXSD)srz.Deserialize(writer);
//srz.Deserialize(item);
break;
I am pasting a snippet of what my xsd looked like:
<xs:complexType name="Parameters">
<xs:all>
<xs:element name="A">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="mstns:Restricted8CharString">
<xs:attribute name="Caption" use="required" fixed="Caption for A">
<xs:simpleType>
<xs:restriction base="xs:string"></xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="ActionWhenMaxReached" use="required">
<xs:simpleType>
<xs:restriction base="xs:short">
<xs:pattern value="[1-3]"></xs:pattern>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Expression" type="xs:string" default="0" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="B">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:short">
<xs:attribute name="Caption" use="prohibited">
<xs:simpleType>
<xs:restriction base="xs:string"></xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="ActionWhenMaxReached" use="required">
<xs:simpleType>
<xs:restriction base="xs:short">
<xs:pattern value="[1-3]"></xs:pattern>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="Expression" type="xs:string" default="0" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:all>
</xs:complexType>
Your closing tag is incorrect. It should be:
</xs:complexType>
and not
</xs:complexType name="Parameters">
After struggling, I have found out the solution:
Actually I was trying to parse an inner element, which was incorrect; I was already having the classes from the xsd tool, so I can Simply use the code as:
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
using (TextReader reader = new StreamReader(filePath))
{
RootClass parameterFromFile = (RootClass)serializer.Deserialize(reader);
}

XSD element with one xml child and then content (including html/xml)

I have an xml document that contains some html.
<begin-line>
<verse-num>6</verse-num>a mixed people<footnote id="f2">
Or <i>a foreign people</i>; Hebrew <i>a bastard</i>
</footnote> shall dwell in Ashdod,
</begin-line>
The verse-num element is the only element I wan't validated, the rest I want valideted to one large group of a string type, which can hold html, and also sometimes some more xml (like footnote).
Here is the schema I have right now which doesn't do the trick.
<xs:element maxOccurs="unbounded" name="begin-line">
<xs:complexType mixed="true">
<xs:sequence minOccurs="0">
<xs:choice maxOccurs="unbounded">
<xs:element name="verse-num">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:unsignedByte">
<xs:attribute name="begin-chapter" type="xs:unsignedByte" use="optional" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
<xs:attribute name="class" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
I am using XSD.exe to generate a class that I can deserialize this junk into.
It is generating a begin-line object with a verse-num type below it, and also an array of text, which are split by the html/xml tags inside of .
What I need is an xsd that can be used by XSD.exe to generate a begin-line class that will give me a verse-num type, and then one string property that will contain the rest of the content (including text, i's, b's, footnotes, xml/html).
I did some research and it seems like processContents will do the trick, but I can't figure out where to put it.
When it comes down to it, I want to program against the object created by the XSD.exe like this.
var beginLine = new crosswaybiblePassageVerseunitBeginline();
Console.WriteLine((beginLine.Items[0] as crosswaybiblePassageVerseunitBeginlineVersenum).Value);
Console.Write(beginLine.Text);
or maybe even...
var beginLine = new crosswaybiblePassageVerseunitBeginline();
Console.WriteLine(beginLine.Versenum.Value);
Console.Write(beginLine.Text);
I'm not sure how to setup the schema such that it'll provide nice output from XSD.exe but you can specify "any number of elements with any name" in the output using a type with the definition:
<xs:complexType name="AnyChildren">
<xs:sequence>
<xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded" namespace="##any"/>
</xs:sequence>
<xs:anyAttribute />
</xs:complexType>
For example to validate:
<Module>
<Title>Hello World</Title>
<ProviderType>xyz</ProviderType>
<Content />
<MoreContent />
</Module>
You could use:
<xs:complexType name="Module">
<xs:sequence>
<xs:element name="Title" type="xs:string" maxOccurs="1" />
<xs:element name="ProviderType" type="xs:string" minOccurs="1" nillable="false" />
<xs:any processContents="skip" minOccurs="0" maxOccurs="unbounded" namespace="##any"/>
</xs:sequence>
<xs:anyAttribute />
</xs:complexType>

Categories