read contents of a xml file into a data grid view - c#

Im using c# .net , windows form application. I have a XML file which contains two columns and some rows of data. now i have to fill this data into a data grid view. im using a button, when i click on the button an open dialog box will appear. i have to select the xml file name and when i click on open the contents of that xml file should come to the data grid view. i have tried with the following code:
{
XmlDataDocument xmlDatadoc=new XmlDataDocument();
XmlDatadoc.Dataset.ReadXml(filename);
ds=xmlDatadoc.Dataset;
datagridview1.DataSource=ds.DefaultViewManager;
datagridview1.Datamember="language";
}
My xml file is:
<languages>
<language>
<key> key1</key>
<value>value1</value>
</language>
<language>
<key> key2</key>
<value>value2</value>
</language>
</languages>
Its working fine but only for "language" . I need it to work file other xml files also.

This one's pretty simple: if you want to use this with a different XML file, use a different Datamember property, like so:
datagridview1.Datamember="taxes"; // or whatever
If you're expecting your DataGridView to somehow magically know what elements in your XML to use for rows, you're out of luck.

Hello i this is example, xml must be in correct format, its easy to correct code if needed, that's just the main gist of idea:
XElement xElement = XElement.Load("file.xml");
DataTable dTable = new DataTable();
// keys must have unique name
xElement.Elements().First().Elements().ToList()
.ForEach(element=>dTable.Columns.Add(element.Name.ToString()));
xElement.Elements().ToList().ForEach((item) =>
{
// fileds must place in the same order
// but you can correct it if you want
var itemToAdd = new List<string>();
item.Elements().ToList().ForEach(field => itemToAdd.Add(field.Value));
dTable.Rows.Add(itemToAdd.ToArray());
}
);
dataGridView1.DataSource = dTable;

Related

C# Webservice response xml displaying as pdf

I am new to C# web development. I am developing a software that receives response from webservice in XML format. (includes barcodes generated by webservice).
There is an option given by webservice provider, that i have to add a line
(Example<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">)
as a second line in the xml and display in web browser by using style sheets provided by webservice provider. If i have to choose this option, how can i add that line as second line in the received xml file also how can i map the style sheets provided by the webserive in the project for this xml.
If i dont take that option, Is it possible to display the data in xml as a pdf(includes barcodes generated by webservice), if i dont choose the option .
If I understand your question correctly, you want to:
Add a stylesheet specification to an existing XML
Convert an XML to PDF
1. ADDING A STYLESHEET
There is an option given by webservice provider, that i have to add a line [...] as a second line in the xml and display in web browser by using style sheets
This is done using e.g. Linq, like in this answer.
First of all, I think the example you used, i.e.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
may be inaccurate, as it is the first line of a XSL file (a stylesheet); those kind of files are used to transform an XML into another file (a different XML or an HTML, like in your case). However, you say
using style sheets provided by webservice provider
so my guess is that you already have those stylesheets and you can you use them, rather than creating them yourself.
If so, the line you want to add is like
<?xml-stylesheet type="text/xsl" href="helloWorld.xsl"?>
Let's suppose you already have your XML stored into an XDocument variable named "Document" with its root element being "Root"
var FilePath = "Example.xml";
var Document = XDocument.Load(FilePath);
var Root = XDocument.Descendants("Root").Single();
Then you can add your stylesheet this way, getting a new XML:
var NewDocument = new XDocument(
new XProcessingInstruction("xml-stylesheet", "type='text/xsl'ref='helloWorld.xsl'"),
Root);
2. XML to PDF
There are several ways to do this.
You might parse your XML, retrieve the elements you want to show on your PDF, use a library like iTextSharp to create a specific layout and place their contents on the file.
Or, since you already have an XML and you can transform it to an HTML using an XSL, you can use wkHtmlToPdf.
Let me know if you need more details.

How to convert more than one GridView to one XML file

my C# WinForms Application has 3 GridViews which I want to save in one XML file.
For one gridview I do it like this:
DataTable dst = new Datatable();
dst = (DataTable)grdViewBGM.DataSource;
dst.TableName = "GridView";
dst.WriteXml(folderPath + String.Format("\\{0}.xml", filename), true);
It may be simple to solve that but I don't have a clue except for making 3 xml files which is everything but perfect.
If someone could give me an advice that would be awesome, thanks.
The created file looks like this:
<?xml version="1.0" standalone="yes"?>
<DocumentElement>
<GridView>
<Genre>Wald</Genre>
<Pfad>C:\Users\Kong\Desktop\Beards\Wald</Pfad>
<Hotkey>1</Hotkey>
</GridView>
<GridView>
<Genre>Wald Nachts</Genre>
<Pfad>C:\Users\Kong\Desktop\Beards\Wald Nachts</Pfad>
<Hotkey>2</Hotkey>
</GridView>
</DocumentElement>
One possible way is to populate the Tables collection of a DataSet. It has a method to write to xml.
void MakeXML(string fileName)
{
DataSet ds = new DataSet();
foreach(DataGridView dgv in this.Controls.OfType<DataGridView>())
{
ds.Tables.Add((DataTable)dgv.DataSource);
}
ds.WriteXml(fileName);
}
If the DataGridView's aren't in the current form(this), use the name of whichever control contains them. If they are spread out, keep a global List<DataGridView> that you add to each time a DataGridView is created, then use that.

C# - Checking if a value exists in a list created from an XML file

I have a small WinForm application that's a basic wallpaper scraper. It has the ability for the user to 'blacklist' a wallpaper so it's never used again. When blacklisted, a wallpapers URL, title and ID are added into an XML file that's in the following format:
<?xml version="1.0" encoding="utf-8"?>
<!--This file stores a list of any wallpapers you blacklist.-->
<Blacklisted>
<Wallpaper>
<URL>http://i.imgur.com/OU3v9H6.jpg</URL>
<Title>Gran Via Madrid Wallpaper [1920x1080]</Title>
<ThreadID>54fsi7</ThreadID>
</Wallpaper>
<Wallpaper>
<URL>http://i.imgur.com/TLXJmGB.jpg</URL>
<Title>The Golden wallpaper HD [1920*1080]</Title>
<ThreadID>55366b</ThreadID>
</Wallpaper>
</Blacklisted>
When a new wallpaper is acquired, there is a quick check to see if the wallpaper URL is in the blacklisted XML file. If it is, then it's not used and a new wallpaper is found. My code for checking if the wallpaper is blacklisted is not actually causing any errors, however the rest of the code after the check is not executing so I believe there is something wrong with my checking process and the code is just getting 'stuck' . Here is my code for checking the XML file:
string url = "http://example.url/image.jpg"
XDocument xml = XDocument.Load("Blacklisted.xml");
var list = xml.Root.Elements("URL").Select(element => element.Value).ToList();
if(list.Contains(url))
{
updateStatus("Wallpaper is blacklisted.");
return;
}
It doesn't look like your list is being populated correctly. Try using the Descendants method from your XDocument object.
var list = xml.Descendants("URL").Select(x=> x.Value).ToList();

Upload XML File to ASP.net Page, Bind Specific Node to GridView (C#)

I am trying to create an ASP.net/C# web page that contains a GridView, and the ability for a user to upload an XML file to that page and bind the grid to a node in that XML. The XML file must be read into memory--not saved to the server first--which has prevented me from modelling this on many online examples which presume an uploaded file is physically sitting on the server when it’s accessed.
The simplified test XML file looks like this, and I do have some latitude to alter or expand it if necessary:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Grids>
<Grid name="GridView">
<item>
<Uno>1A</Uno>
<Dos>1B</Dos>
<Tres>1C</Tres>
</item>
<item>
<Uno>2A</Uno>
<Dos>2B</Dos>
<Tres>2C</Tres>
</item>
<item>
<Uno>3A</Uno>
<Dos>3B</Dos>
<Tres>3C</Tres>
</item>
<item>
<Uno>4A</Uno>
<Dos>4B</Dos>
<Tres>4C</Tres>
</item>
</Grid>
</Grids>
</root>
The client needs to be able to click on a FileUpload control, browse to a local XML file, and have the grid reflect the data in the node named "GridView" above. I can’t figure out how to extract just that node from the XML data. If I create a cut-down, poorly formed XML file with that node as the root, it works, but I don’t want to do that as I plan on expanding this in the future.
Below is the salient portion of the ‘import’ code I have at the moment. It’s not optimal – I got here through trial and error so there’s probably a lot of garbage in here. When I run this, I get a single-cell grid that just contains the text “Grid_Id” rather than the tabular data I need (although even that’s broken at the moment).
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".xml")
{
using (MemoryStream stream = new MemoryStream(FileUpload1.FileBytes)) // Using FileBytes because I can’t save file to server
{
XmlDocument document = new XmlDocument();
document.Load(stream);
stream.Position = 0;
string xmlFile;
using (StreamReader inputStreamReader = new StreamReader(FileUpload1.PostedFile.InputStream))
{
xmlFile = inputStreamReader.ReadToEnd();
}
XmlTextReader reader = new XmlTextReader(new StringReader(xmlFile));
DataSet dataSet = new DataSet();
dataSet.ReadXml(reader);
//gv1.DataSource = dataSet.Tables[“GridView”]; // Doesn’t work
gv1.DataSource = dataSet.Tables[0];
gv1.DataBind();
}
}
}
}
Ultimately I’d like to create a more generic component that will allow us to any save grid data to a user’s desktop and push that ‘snapshot’ back in to the grid at a later date. Thanks in advance for any guidance (this is my first post)!

How to use a text file containing a list of words as a drop down menu for html?

I am trying to create a drop down menu in an ASP.NET using a text file as the list elements. I want to create the menu from the text file so I can easily add or delete different options without adding the ASP.NET source code. Also, how could I store new options as variables in ASP.NET when more options are added to the text file? My code-behind is c#.
Thanks all,
Stephen
you can do this several ways.. lets say you have a file with a list of items named menuItems.txt you could do something like this
if the list were like this for example
Open
SaveAs
Save
Exit ....ect you get the drift
List<string> lstMenuItems =
new List<string>(File.ReadAllLines(strFilePath+ menuItems.txt));//make this a variable.
this will read all the items in a list and then from there you could Create the MenuItem object and load the ites from the lstMenuItems
If you haven't actually created the text file yet, I would suggest creating an XML text file for this, then using LINQ to XML to pull the values out, and bind them to your dropdown.
Search on those keywords to find the details on how to do those things.
your XML file might look like this:
<?xml version="1.0"?>
<dropDownValues>
<entry>
<text>Dog</text>
<value>1</value>
</entry>
<entry>
<text>Cat</text>
<value>2</value>
</entry>
<entry>
<text>Canary</text>
<value>3</value>
</entry>
</dropDownValues>
Then query the data like this:
var xDoc = XDocument.Load(pathToXmlDocument);
// Return an "anonymous" type that represents your XML document:
var dropDownValues = xDoc.Descendants("entry")
.Select(x => new
{
Text = x.Element("text").Value,
Value = x.Element("value").Value
});
Then bind to your drop down:
myDropDown.DataSource = dropDownValues;
myDropDown.DataTextField = "Text";
myDropDown.DataValueField = "Value";
myDropDown.DataBind();

Categories

Resources