I have an XML file that I have no write access to it .. I retrieve it online.
I have the code below, which works fine, but I can't move forward ..
using System.Data;
using System.Xml.Linq;
try
{
XDocument XMLFile = XDocument.Load(@"http://Domain/path/to/file.xml");
MessageBox.Show("Remote File Loaded Successfully ...");
var items = XMLFile.Descendants("item");
int i = 0;
foreach (var item in items)
{
i++;
//var title = item.Descendants("title");
//MessageBox.Show(title.ToString());
}
MessageBox.Show("Items Found: " + i);
}
catch(exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString());
MessageBox.Show("Error: " + ex.InnerException.ToString());
}
The problem I'm facing is in the foreach
loop. Every root element item has some child elements. I can't figure out how to retrieve those elements!!
Also, I have a grid view, I want to add the result to it, how can I achieve that??
Thank.
EDIT
XML Sample:
<item>
<title>Title</title>
<link>http://domain/link</link>
<description>Some Text</description>
<pubDate>Wed, 05 Dec 2012 01:29:37 -0500</pubDate>
<guid isPermaLink="false">Domain_text_INTEGER</guid>
<category domain="http://domain/link">A</category>
<category domain="http://domain/link">B</category>
<category domain="http://domain/link">C</category>
<category domain="http://domain/link">D</category>
<category domain="http://domain/link">E</category>
<coop:keyword>A</coop:keyword>
<coop:keyword>B</coop:keyword>
<coop:keyword>C</coop:keyword>
<coop:keyword>D</coop:keyword>
<coop:keyword>E</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>Text</coop:keyword>
<coop:keyword>text integer</coop:keyword>
<coop:keyword>Text</coop:keyword>
</item>
What I need from it:
Thanks.
So on your XMLfile XDocument you've got the descendants.
Also create a collection
List<someobject> list = new List<someobject>();
So in your loop
foreach (var item in items)
{
var someObject = new SomeObject()
{
Title = item.Element("title").Value
}
}
Then bind your collection to the Grid
This MSDN topic could help you. On MSDN they are posted Walk-through of your problem. Both links suggest to use dataset for this:
DataSet dsAuthors = new DataSet("authors");
string filePath = "Complete path where you saved the XML file";
dsAuthors.ReadXml(filePath);
dataGrid1.DataSource = dsAuthors;
dataGrid1.DataMember = "authors";
dataGrid1.CaptionText = dataGrid1.DataMember;
I just copy/paste an example. You need to modify it for your purposes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.