I have a C# application that calls a stored procedure that produces an xml result (using FOR XML Explicit) that I want to save to disk. Doing some research I have found the following method:
var data = new DataSet();
XmlReader reader = cmd.ExecuteXmlReader();
data.ReadXmlSchema(reader);
data.ReadXml(reader, XmlReadMode.Fragment);
data.WriteXml(filename);
However this outputs the following in the file:
<?xml version="1.0" standalone="yes" ?>
<NewDataSet />
I think this method might only work for XML Raw and XML Auto however I can look through the dataset's tables and see the data is there.
UPDATE: I was able to get it to work by not reading the XmlSchema and by not specifying the XmlReadMode.
I was able to get it to work by not reading the XmlSchema and by not specifying the XmlReadMode.
Related
Accidently, I stumpled across a misformatted XML file having this content:
<?xml version="1.0" encoding="utf-8"?>
<MainModel xmlns:ctl="http://schemas.catelproject.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" ctl:graphid="1">
<DataId>123</DataId>
<DataName>Main Data Name</DataName>
<DataCollection ctl:graphid="2">
<SubModel ctl:graphid="3" xmlns:d0p0="http://schemas.datacontract.org/2004/07/CatelSpoiledDerialization.Models" i:type="d0p0:SubModel">
<SubId>200</
As the XML code shows, my example project (https://github.com/thoblerone/CatelSpoiledDerialization) is using the Catel framework, but deep debugging points towards a possible issue in System.Runtime.Serialization.XmlReader
The code to deserialize is pretty straght forward
var iXmlSer = SerializationFactory.GetXmlSerializer();
using var fileStream = File.Open(res.FileName, FileMode.Open);
var myData = iXmlSer.Deserialize<MainModel>(fileStream);
Yet, the call to Deserialize will never finish. Stepping through with the debugger, I see that the underlying .net XmlReader is calling MoveToContent while pointing to defective element (SubId) but the call will never succeed nor does it throw an exception, which I would gladly accept.
Am I missing come xml reader configuration that would check file conformity before tryinto to read the stuff?
I want to get the data from XML File using C# and i need to assign this data to a dto. Here i need to consider performance also when getting the data from xml file. I already used xml deserialization to get the data from xml file but it is taking lot of time to get the data from large xml files. Please suggest me a solution considering performance using C#.
If your XML file is too huge then you can use the XMLReader. Also you can look into the LINQ to XML option.
Example:
<Branch>
<Node>
<MyNode>
<SubNode code=\"0\">
My message
</SubNode>
</MyNode>
</Node>
</Branch>
Using LINQ to XML
var doc = XDocument.Parse(xml);
var subnode = from x in doc.Descendants("SubNode")
select new
{
code = x.Attribute("code").Value,
msg = x.Value.Trim()
};
foreach (var e in subnode)
{
}
I started with three (3) XSD files provided from an external party (one XSD links to the other two). I used the xsd.exe tool to generate a .NET object by running the following command: xsd.exe mof-simpleTypes.xsd mof-isp.xsd esf-submission.xsd /c and it generated a single CS file with a handful of partial objects.
I've created an XmlSerializerNamespaces object and fill with the namespaces required (two directly used in the provided sample XML file as well as two others that don't appear to be referenced). I have successfully generated an XML file using the following method:
private XmlDocument ConvertEsfToXml(ESFSubmissionType type)
{
var xml = new XmlDocument();
var serializer = new XmlSerializer(type.GetType());
string result;
using (var writer = new Utf8StringWriter()) //override of StringWriter to force UTF-8
{
serializer.Serialize(writer, type, _namespaces); //_namespaces object holds all 4 namespaces
result = writer.ToString();
}
xml.LoadXml(result);
return xml;
}
My problem that I'm facing is in the generated CS file, one of the objects has a property (another generated partial object) that is of type XmlElement. I have successfully built the object in code, and I'm having an issue converting the object to an XmlElement. The questions and answers I have found here on SO say convert it to an XmlDocument first and then take the DocumentElement property. This works, however the returned XML has namespaces embedded in the element as follows:
<esf:ESFSubmission xmlns:isp="http://www.for.gov.bc.ca/schema/isp" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:esf="http://www.for.gov.bc.ca/schema/esf">
<esf:submissionMetadata>
<esf:emailAddress>test#test.com</esf:emailAddress>
<esf:telephoneNumber>1234567890</esf:telephoneNumber>
</esf:submissionMetadata>
<esf:submissionContent>
<isp:ISPSubmission xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:esf="http://www.for.gov.bc.ca/schema/esf" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:isp="http://www.for.gov.bc.ca/schema/isp">
<isp:ISPMillReport>
<isp:reportMonth>12</isp:reportMonth>
<isp:reportYear>2014</isp:reportYear>
<isp:reportComment>comment</isp:reportComment>
<isp:ISPLumberDetail>
<isp:species>FI</isp:species>
Note: this is just a partial of the generated XML file (for illustration purposes).
As you can see, each XML node is prefixed with the namespace variable. My question is: how can I do this in code? Is my approach sound and if so, then how do NOT include the namespaces in the ISPSubmission node OR if there is a better way to approach this problem that I overlooked, please provide insight. My desired outcome is to have all namespace definitions at the top of the document (their appropriate location) and not on the sub elements - as well as maintain the namespace variables on each element as illustrated above.
EDIT (after reggaeguitar's comment)
Here is the sample XML document I was provided
<?xml version="1.0" encoding="UTF-8"?>
<esf:ESFSubmission xmlns:esf="http://www.for.gov.bc.ca/schema/esf"
xmlns:isp="http://www.for.gov.bc.ca/schema/isp" xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.for.gov.bc.ca/schema/esf esf-submission.xsd
http://www.for.gov.bc.ca/schema/isp mof-isp.xsd">
<esf:submissionMetadata>
<esf:emailAddress>mailto:eric.murphy#cgi.com</esf:emailAddress>
<esf:telephoneNumber>6044445555</esf:telephoneNumber>
</esf:submissionMetadata>
<esf:submissionContent>
<isp:ISPSubmission>
<isp:ISPMillReport>
<isp:reportMonth>06</isp:reportMonth>
<isp:reportYear>2014</isp:reportYear>
<isp:reportComment>Up to 4000 characters is permitted for notes in this element.</isp:reportComment>
<isp:ISPLumberDetail>
<isp:species>FI</isp:species>
<isp:lumberGrade>EC</isp:lumberGrade>
<isp:gradeDescription/>
<isp:size>2x4</isp:size>
<isp:finishType/>
<isp:length>10</isp:length>
<isp:thickWidthUom>IN</isp:thickWidthUom>
<isp:volumeUnitOfMeasure>MBM</isp:volumeUnitOfMeasure>
<isp:volume>11543.987</isp:volume>
<isp:amount>1467893.98</isp:amount>
<isp:invoiceNumber>837261</isp:invoiceNumber>
</isp:ISPLumberDetail>
<isp:ISPLumberDetail>
<isp:species>CE</isp:species>
<isp:lumberGrade/>
<isp:gradeDescription/>
<isp:size/>
<isp:finishType>D</isp:finishType>
<isp:thickness>40</isp:thickness>
<isp:width>100</isp:width>
<isp:thickWidthUom>MM</isp:thickWidthUom>
<isp:volumeUnitOfMeasure>MBM</isp:volumeUnitOfMeasure>
<isp:volume>9743.987</isp:volume>
<isp:amount>1247893.98</isp:amount>
<isp:invoiceNumber/>
</isp:ISPLumberDetail>
<isp:ISPChipDetail>
<isp:species>CE</isp:species>
<isp:unitOfMeasure>BDT</isp:unitOfMeasure>
<isp:wholeLogInd>N</isp:wholeLogInd>
<isp:destinationCode>FBCO</isp:destinationCode>
<isp:destinationDescription/>
<isp:volume>563</isp:volume>
<isp:amount>54463</isp:amount>
<isp:invoiceNumber>12345679</isp:invoiceNumber>
</isp:ISPChipDetail>
</isp:ISPMillReport>
<isp:ISPSubmitter>
<isp:millNumber>103</isp:millNumber>
<isp:contactName>Dave Marotto</isp:contactName>
<isp:contactEmail>eric.murphy#cgi.com</isp:contactEmail>
<isp:contactPhone>2507775555</isp:contactPhone>
<isp:contactPhoneExtension>1234</isp:contactPhoneExtension>
</isp:ISPSubmitter>
</isp:ISPSubmission>
</esf:submissionContent>
</esf:ESFSubmission>
Solved my problem by doing the whole thing in code and not even using the xsd.exe to generate a .NET object.
I have generated an XML file by exporting my SQLite database in c#.net.My generated XML is like-
<root>
<name1>
<names>
<id>5</id>
<from>Germany</from>
<to>France</to>
<through>
<via>
<id>7</id>
<routeNo>5<routeNo>
<route>Vienna<route>
</via>
</through>
</names>
<names>
<id>10</id>
<from>US</from>
<to>Canada</to>
<through>
<via>
<id>8</id>
<routeNo>10<routeNo>
<route>Mexico<route>
</via>
</through>
</names>
</name1>
</root>
I am trying to import this XML file and insert all the data back into an empty SQLite database. I need to verify the contents before inserting into SQLite database. I have created an XSD file from my existing XML file.i used NDbUnit library here. My codes for importing the data from the XML into SQLite database are following -
string connectionString = "Data Source=emptyDB.sqlite;Version=3;New=True;Compress=True;";
NDbUnit.Core.INDbUnitTest Database = new NDbUnit.Core.SqlClient.SqlDbUnitTest(connectionString);
Database.ReadXmlSchema("myFlatXml.xsd");
Database.ReadXml("myFlatXml.xml");
Database.PerformDbOperation(NDbUnit.Core.DbOperationFlag.CleanInsertIdentity);
I have used XSD file which is generated from XML file, but it seems, I have to create the XSD from my sqlite database. the problem is sqlite manager does not support exporting database to XSD file. Moreover, i can't find any clear documentation for crating the XSD using NDbUnit. Could anyone help please ?
The NDbUnit framework does exactly what you need. So no need to get your hands dirty.
Also available via NuGet.
I have this xml file
<?xml version="1.0" encoding="utf-8" ?>
<parameters>
<parameters
registerLink="linkValue"
TextBox.name="nameValue"
/>
</parameters>
I want to print off "LinkValue" and "nameValue" by code:
Console.WriteLine("registerLink: " + registerLink);
Console.WriteLine("TextBox.name: " + TextBox.name);
Thanks
The easiest API is XLinq (System.Xml.Linq)
var doc = XDocument.Load(fileName);
// This should be parameters/parameter, i follow the question with parameters/parameters
var par = doc.Element("parameters").Element("parameters");
registerLink = par.Attribute("registerLink").Value; // string
Your could use an xml reader like this one
http://msdn.microsoft.com/en-us/library/cc189056%28v=vs.95%29.aspx
Once you have a working sample look here to find out how to open an xml reader from a file stream. File must be located in project directory
http://support.microsoft.com/kb/307548
Once you have that done you can add an open file dialog box to find any file on the computer and even validate the .xml extension and more.
Edit: As you can see in the comments below, Hanks solution is better, faster, and easier. My solution would only be useful if you have huge xml files with tons of data. You may still be interested in the file dialog box as well.