How do I retrieve data from an XML file? - c#

I have an XML file and I want to retrieve data from it so I can store this data in my database. I've searched and I found this post.
I don't know what the following means:
Create a XML schema so you can deserialize this XML into a .NET object - works best if you have tons of those files to import.
So:
I'd like to see some articles or examples of how to do this.
How do I check data that comes from an XML file?

This means that you can write a .NET object that reflects the structure of your XML file and then deserialize the XML file back to an instance of this object. For example if you have the following XML:
<User>
<FirstName>John</FirstName>
<LastName>John</LastName>
</User>
you could have a User class:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
and then deserialize:
var serializer = new XmlSerializer(typeof(User));
using (var reader = XmlReader.Create("test.xml"))
{
User user = (User)serializer.Deserialize(reader);
}
You can apply attributes to the .NET object in order to control the serialization/deserialization process.
As far as the validation of the XML file is concerned you could write a XSD schema (which is a XML file) representing the data structure of your file and then validate it against this schema. This will ensure that the XML file you have as an input obeys the defined rules (it has the correct node names, required properties, ...).

You want to know about "Create a XML schema so you can deserialize this XML into a .NET object - works best if you have tons of those files to import".
Here is the link that shows you how to achieve that:
Instructions

You can create schema using Visual studio. Just open XML file with VS. Then select XML->Create schema menu.
Or you can use Xsd.exe tool :
First extract shema using command
xsd.exe your.xml
Second generate
classes from generated schema using
command xsd.exe your.xsd /classes
And here you can find how to validate xml using xsd.

Related

Dynamic XML parsing, data storage, and forms in c#

So I am developing an application that I want to be able to dynamically parse an xml file, grab attributes and populate a form that is created based on what elements are present in the xml file. Then the values can be edited, and written back to the xml file that was originally opened.
I've been able to parse, save values to a database , populate forms, and write back to the original xml file via hard coding, and I think I have an idea for the dynamic "database" structure (a dictionary where the key is a node's name, and the value is a dictionary if I wanna store a node's child node information, or a string if I'm in the furthest nested child node of an element).
I'm stuck on how to grab the information I need and how to store it in the "database" structure I've come up with. I've done research and have seen people use the "dynamic" object and linq. But everything I've seen seems to involve knowing the path names they've needed before run time. Any ideas on how I should be going about actually parsing the file and grabbing data, first off? I think if I can get that figured out, the rest should kind of fall into place.
Say I have this xml
<users>
<user1 age="43">John Doe</user1>
<user2 age="40">Jane Doe</user2>
</users>
An example database setup would look like Dictionary<users, Dictionary<user1, Dictionary<name,John Doe>
Where you could go Key("users").Key("user1").Key("name").Value to get John Doe or something like that.
Any other suggestions for my database setup would also be appreciated
It sounds like what you are looking for is XML serialization. Before you can do that though, you need to simplify your xml. Instead of numbering the <user> elements, you will want to use an attribute that has the value for the user id. For example you can use an id attribute.
<users>
<user id="1" age="43">John Doe</user>
<user id="2" age="40">Jane Doe</user>
</users>
Once you have done this, create a class that you can serialize to this xml.
using System.Xml.Serialization;
[XmlRoot(ElementName = "users")]
public class Users : List<User>
{
}
[XmlType(TypeName = "user")]
public class User
{
[XmlAttribute(AttributeName = "id")]
public int Id { get; set; }
[XmlAttribute(AttributeName = "age")]
public int Age { get; set; }
[XmlText]
public string Name { get; set; }
}
Then all you have to do to load from the file is deserialize.
XmlSerializer serializer = new XmlSerializer(typeof(Users));
Users users = (Users)serializer.Deserialize(File.OpenRead("XMLFile1.xml"));
You can use LINQ to query the Users collection for specific users.
var user1 = users.Where(u => u.Id == 1)
Modify the User objects or add more to the Users collection, then serialize to save changes back to the file.
XmlSerializer serializer = new XmlSerializer(typeof(Users));
serializer.Serialize(File.OpenWrite("XMLFile1.xml"), users);
You could parse xml using XmlDocument class. After parsing you have tree of nodes which you can traverse and show in UI. I don't understand why you want to save xml as distinct records of values in database, just save it as text. Anyway for saving xml you should translate its records back to xml.

Bind any XML & XSD to DataGridView c#

I have a DataGridView which I populate with data from an XML using XmlSerializer and a class that is used for serialization.I validate the xml using an XML schema.
I was wondering if there is a way to bind any xml with a gridview without the need to use the extra class for serialization.
I would like to be able to feed the application an XML and a XSD schema for validation and the aplication would fill the DataGridView automatically, no matter what xml it would receive, how could I achieve this?
*The XML file should be simple.
IEnumerable<string> dataSrc= (from ds in XDocument.Load(#"pathOfYourXMLFile").Descendants("TagName")
where ds.Element("elementName").Value == env
select ds.Attribute("NameOfAttribute").Value);
You can read XML using XDocument or XmlDocument class - to get all values.
Problem is, that you first have to specify datagridview columns, so first you have to read whole xml to get all elements it contains and then decide which one would you like to show in the table.

Deserialization with options

I am currently achieving serialization of a collection to the file. The results are like how I expect
<Persons>
<Person>
<Identity>1234</Identity>
<Name>asd</Name>
</Person>
<Person>
<Identity>12345</Identity>
<Name>asdd</Name>
</Person>
</Persons>
Now, I don't want to deserialize the whole collection but I want to deserialize an object from the file with some specific options. For example,
object GetPersonWithIdentity(int identity )
{
// what to do here
}
object asd = GetPersonWithIdentity(1234);
// expected Person with Identity "1234" and Name "asd"
Is it be reasonable to deserialize whole collection and find the specific object and return it, or is there any other solution for this?
XML is not seekable so you at least have to read forward till you find the first match. The framework does not support that automatically so you have to do it manually using an XmlReader which is laborious.
If the file is small and/or performance is not an issue, just deserialize everything and be done with it.
If your dataset is big I'd consider moving to some more scalable format like an embedded SQL database. SQL databases have this capability inherently.
You will have to serialize the entire XML file because as usr mentioned, XML is forward only. XmlReader/Writer is essentially a TextReader (Stream) object, and is doing file i/o to read an XML file.
The reason for my seperate answer is I would do the following using an XDocument object:
object GetPersonWithIdentity(int identity )
{
return myXDocumentVaraible.Descendants("Person")
.First(person => person.Element("Identity").Value == identity.ToString());
}

How to Retrieve data and want to read data from XML in C#

I am using windows application and I have four combo boxes(comboeventname,combosendtype,comboType,comboschedule) in that form.... I have stored that combo values in to XML file by using XML writer...
Now I want to display the data in that combo boxes in form load event when form opens in run time... How to retrieve that values from that XML file and how to display that data in combo boxes while run time? How shall I do this?
Anyone tell me the solution of this.....
Thanks in Advance...
We can probably get XmlReader working if you show the xml or the code you used to write it, but I'm not sure that is the best option here. Presumably, to display them in a combobox the data-volume isn't immense. In that case, it would be much simpler to use any of:
XmlDocument
XDocument
XmlSerializer
etc to load the data into a DOM or object-model, and work from their. LINQ-to-XML (via XDocument) may be particularly appealing. For example, with the xml:
<options>
<option value='123'>ABC</option>
<option value='234'>DEF</option>
<option value='567'>GHI</option>
</options>
The XDocument code like below may work:
var options =
from option in XElement.Parse(xml).Elements("option")
select new {
value = (int)option.Attribute("value"),
text = option.Value
};
Probably much easier to use XmlDocument , or XDocument.
XmlDocument:
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.selectsinglenode.aspx
private void Form1_Load(object sender, EventArgs e)
{
//load the xml document;
XmlDocument xdoc = new XmlDocument;
xdoc.Load("YourFile.xml");
// read the values
// using indexers
method1 = xdoc["root"]["Element"].Value;
// using xpath to select nodes
method2 = xdoc.SelectSingleNode( "root/element/element" ).Value;
// attributes
method3 = xdoc.SelectSingleNode("root/element").Attributes["YourAttribute"].Value;
}
XmlReader is better used for large XML files, 1000s of elements, where you don't want to load the whole document into memory. Your document sound far to small to use XmlReader.
I'd suggest using an XmlReader. There's a lot of documentation around but here's a start:
http://msdn.microsoft.com/en-us/library/9d83k261%28VS.80%29.aspx
Once you have the data you can add them to the your form controls.
Alternatively you could use an XmlDocument - although it does not perform as well as the XmlReader I doubt you will notice with this situation.
I have used before xsd mappings to generate class mappings for an xml document.
On visual studio command prompt line use xsd commands like below .
This will generate mapping class and then
you should deserialize xml file to object and cast to generated mapping class.
xsd "path of xml file" this genarates xsd file
than command promt again
xsd "pat of generated xsd file" /CLASSES
for details look at that sample

what's the best way to automate generation of an xsd given an xml sample?

I have a chunk of xml data that's coming out of a database that I need to generate an xsd for. Got it all working using xsd.exe but all the elements are showing up as string, even things like 2079.0200. How do I get xsd.exe to guess at types? Would the XmlSchemaExporter class be able to do this?
The issue here is that Visual Studio is generating the xsd that I want (with decimal types etc) when I use the XML --> Create Schema command, but I don't want to have to do this by hand. I'm setting up a process that takes in a chunk of xml and generates an XSD. But it needs to have more types than just "string".
Related, but don't know if it's a solution yet (XmlSchemaInference class): Any tools to generate an XSD schema from an XML instance document?
The solution is to create the schema by hand, based on the one that's been generated. Then don't run XSD.EXE again.
John's answer is valid for situations where accuracy is more important than speed. For my situation, I needed many schemas that were identical to what would be produced via the VS "Create Schema" command. So accuracy wasn't as important as matching a known baseline and speed.
This is what I ended up doing. It produced output identical to the VS "Create Schema" command:
XmlSchemaInference inf = new XmlSchemaInference();
// xml variable on the next line is a string being passed in
XmlSchemaSet schemas = inf.InferSchema(new XmlTextReader(xml, XmlNodeType.Element, null));
schemas.Compile();
XmlSchema[] schemaArray = new XmlSchema[1];
schemas.CopyTo(schemaArray, 0);
XmlTextWriter wr = new XmlTextWriter(xsdOutputFileNameAndPath, Encoding.UTF8);
wr.Formatting = Formatting.Indented;
schemaArray[0].Write(wr);
wr.Close();

Categories

Resources