How to get data from xml, by linq, c# - c#

Hi,
I have a problem with getting data from youtube xml:
address of youtube xml: http://gdata.youtube.com/feeds/api/videos?q=keyword&orderby=viewCount
I try this, but the program doesn't go into the linq inquiry.
key = #"http://gdata.youtube.com/feeds/api/videos?q="+keyword+#"&orderby=viewCount";
youtube = XDocument.Load(key);
urls = (from item in youtube.Elements("feed")
select new VideInfo
{
soundName = item.Element("entry").Element("title").ToString(),
url = item.Element("entry").Element("id").ToString(),
}).ToList<VideInfo>();
Anyone has idea, how to solve this?
Thanks!

Searching for elements in Linq to XML requires that you fully qualify with the namespace. In this case:
var keyword = "food";
var key = #"http://gdata.youtube.com/feeds/api/videos?q="+keyword+#"&orderby=viewCount";
var youtube = XDocument.Load(key);
var urls = (from item in youtube.Elements("{http://www.w3.org/2005/Atom}feed")
select new
{
soundName = item.Element("{http://www.w3.org/2005/Atom}entry").Element("{http://www.w3.org/2005/Atom}title").ToString(),
url = item.Element("{http://www.w3.org/2005/Atom}entry").Element("{http://www.w3.org/2005/Atom}id").ToString(),
});
foreach (var t in urls) {
Console.WriteLine(t.soundName + " " + t.url);
}
Works for me. To avoid writing out the namespace, one option is to search by local name (e. g. youtube.Elements().Where(e => e.LocalName == "feed"). I'm not sure if there's a more elegant way to be "namespace agnostic".

Related

How can i access to the Value that i scraped and Add it to my DataGrid? Pls Look at the screenshot

public void ScrapeData(string page)
{
var web = new HtmlWeb();
var doc = web.Load(page);
var Articles = doc.DocumentNode.SelectNodes("//*[#class = 'b-product-grid-tile js-tile-container']");
foreach (var article in Articles)
{
var Sneaker = HttpUtility.HtmlDecode(article.SelectSingleNode(".//span[#class ='b-product-tile-link js-product-tile-link']").InnerText);
var Preis = HttpUtility.HtmlDecode(article.SelectSingleNode(".//div[#class ='b-product-tile-price']").InnerText);
var hrefList = doc.DocumentNode.SelectNodes("//a").Select(p => p.GetAttributeValue("href", "not found"));
Debug.Print(Sneaker + Preis + hrefList);
_entries.Add(new EntryModel { Products = Sneaker, Preis = Preis, Link = hrefList }); // canĀ“t convert string implicitly (Sory i have Visual Studio in German i try to translate the Error)
}
All the Links But how can i access to them? and get them in my DataGrid
I found the Links but idk how i access to them and get it into my DataGrid
After i add .ToArray i got the same problem the Debugger Print alwayse (System.Linq.Enumerable+WhereSelectEnumerableIterator`2[HtmlAgilityPack.HtmlNode,System.String])
Here some screenshots of the edited code
Same Problem
The Edit Code
And again i am very sorry how i ask my questions i am very new and i am happy if you correct me
It's not completely clear which of the links you want; you've highlighted only one. However if you do:
var hrefList = doc.DocumentNode.SelectNodes("//a")
.Select(p => p.GetAttributeValue("href", "not found"))
.ToArray();
(added .ToArray())
Then you can access e.g. the second one via hrefList[1]
If you only ever want the second one you;d be better off doing:
var href = doc.DocumentNode.SelectNodes("//a")
.Select(p => p.GetAttributeValue("href", "not found"))
.Skip(1)
.First();
No need to copy the whole lot to an array if all you want is one

Trying to compare tags in mongodb string array, with textbox input c#

Okay so i have a mongodb that has a collection that is called videos and in videos i have a field called tags. what i want to do is compare a textbox input with the tags on all videos in the collection and return them to a gridview if a tag matches the input from the textbox. When i create a new video the tags field is a string Array so it is possible to store more than one tag. I am trying to do this in c#. Hope you some of you can help thanks!
Code for creating a new video document.
#region Database Connection
var client = new MongoClient();
var server = client.GetServer();
var db = server.GetDatabase("Database");
#endregion
var videos = db.GetCollection<Video>("Videos");
var name = txtVideoName.Text;
var location = txtVideoLocation.Text;
var description = txtVideoDescription.Text;
var user = txtVideoUserName.Text;
string[] lst = txtVideoTags.Text.Split(new char[] { ',' });
var index = videos.Count();
var id = 0;
if (id <= index)
{
id += (int)index;
}
videos.CreateIndex(IndexKeys.Ascending("Tags"), IndexOptions.SetUnique(false));
var newVideo = new Video(id, name, location, description, lst, user);
videos.Insert(newVideo);
Okay so here is how the search method looks like i have just made the syntax a little diffrent from what Grant Winney ansewred.
var videos = db.GetCollection<Video>("Videos");
string[] txtInput = txtSearchTags.Text.Split(new char[] { ',' });
var query = (from x in videos.AsQueryable<Video>()
where x.Tags.ContainsAny(txtInput)
select x);
This finds all videos with tags that contain a tag specified in the TextBox, assuming the MongoDB driver can properly translate it into a valid query.
var videos = db.GetCollection<Video>("Videos")
.AsQueryable()
.Where(v => v.Tags.Split(',')
.ContainsAny(txtVideoTags.Text.Split(',')))
.ToList();
Make sure you've got using MongoDB.Driver.Linq; at the top.

c# xml parsing - conversion from php

I currently have my application/project setup on PHP and I am trying to get it working in c# so I can build an application around it.
I have come across some parts of the code which I am looking help with.
XML data from: http://api.eve-central.com/api/marketstat?usesystem=30000142&hours=48&typeid=34&typeid=456
Above is XML data from a certain system containing 2 typeids (same as the other XML), again this will be around 100 items at a time.
I am using this code at the moment:
XDocument doc = XDocument.Load("http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&usesystem=30000142");
var id = from stats in doc.Root.Elements("marketstat")
from type in stats.Elements("type")
select new
{
typeID = type.Attribute("id").Value
};
foreach (var itemids in id)
{
kryptonListBox4.Items.Add(itemids.typeID);
};
Which populates the ListBox as 34 and 456.
What I need is to be able to add the other xml data such as min sell and max buy
I can get the first min sell like this:
string minSell = doc.Descendants("sell")
.First()
.Element("min")
.Value;
But I need to have the minsell in relation to the typeID and being able to work with the data.
Second Problem
XML data from http://api.eve-marketdata.com/api/item_history2.xml?char_name=demo&days=10&region_ids=10000002&type_ids=34,456
Above is XML data from a certain region and contains 2 type_ids (this will be a much larger list when completed around 100 items at a time).
I have tried to use similar code as above but I cannot get it to return the correct data.
I need to be able to get the volume in total for each typeid
In PHP I use this:
foreach ($xml -> result -> rowset-> row as $row)
{
$id = (string)$row['typeID'];
$volume = $row['volume'];
if (!isset($volumes[$id]))
{
$volumes[$id] = 0;
}
$volumes[$id] = $volumes[$id] + $volume;
}
Any help would be greatly appreciated!
//Edit: Looks like I can use
var vRow = from xmlRow in marketstats.Descendants("emd").Descendants("result").Descendants("rowset").Descendants("row")
select xmlRow;
for the 2nd problem but I cannot seem to get the multidimensional array to work
For your second problem if my understanding is right this will be close to ur need.
var strxml = File.ReadAllText(#"D:\item_history2.xml");
var xml = XElement.Parse(strxml);
var typeIDs = (from obj in xml.Descendants("row")
select obj).Select(o => o.Attribute("typeID").Value).Distinct();
Dictionary<string, long> kv = new Dictionary<string, long>();
foreach (var item in typeIDs)
{
var sum = (from obj in xml.Descendants("row")
select obj).Where(o => o.Attribute("typeID").Value == item).Sum(p => long.Parse(p.Attribute("volume").Value));
kv.Add(item, sum);
}
In the dictionary you will have the sum of volumes against each typeID in such a way
typeID as key and sum of volume as value in Dictionary kv.
For your first problem,
Checkout this,
var minsell = (from obj in xml.Descendants("type")
select new
{
typeid = obj.Attribute("id").Value,
minsell = obj.Descendants("sell").Descendants("min").FirstOrDefault().Value
}
).ToArray();
This will give you minsell value in relation with typeid.
I guess this what you expects ?
If wrong please comment it.

List 'areas' used in TFS project

I've been playing about with the WorkItem objects from the Microsoft.TeamFoundation schemas in C#, but was wondering if anyone knows how I would refer to an object of type 'Area' or, for that matter, 'Iteration'.
It seems that these are treated as objects in TFS, but I haven't come across any information on how to refer to these in C#.
You can filter WorkItems by [Area] or [Iteration] using WIQL, but what if I wanted to populate a ComboBox with all Areas or Iterations?
Also, how can I view the database structure of my workplace's TFS project?
Thanks guys,
Andy
Have a look at this Blog Post. There's sample code and a demo.
Here's a quick LINQPad Query that should do the job (download VS2010 / VS2012):
void Main()
{
const String CollectionAddress = "http://tfsserver:8080/tfs/MyCollection";
const String ProjectName = "MyProject";
using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri(CollectionAddress)))
{
tfs.EnsureAuthenticated();
var server = tfs.GetService<ICommonStructureService>();
var projectInfo = server.GetProjectFromName(ProjectName);
var nodes = server.ListStructures(projectInfo.Uri).Dump();
// You should be able to re-factor this with "Iteration"
// for getting those too.
var nodesXml = server.GetNodesXml(
nodes
.Where(node => node.Name == "Area")
.Select(node => node.Uri).ToArray(),
true);
var areaPathAndId =
XElement.Parse(nodesXml.OuterXml)
.Descendants("Node")
.Select(xe => new
{
Path = xe.Attribute("Path").Value,
ID = xe.Attribute("NodeID").Value,
})
.Dump();
}
}

Retrieve all items from a SharePoint Field Choice Column with using ObjectModel

I know a similar question has already been asked, but that retrieves all the items for Choice field using Sharepoint Object Model. I dont have object model available to me. I want to do this using CAML or something. I couldnt figure out a CAML query to get all the items for a choice field.
Any pointers in the right direction will be really appreciated.
Regards.
Can you use web service calls? This thread explains reading multi-choice choices from a web service: http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/04a00936-7102-4ddc-aa7d-0be7e14e7692
This follow-up post might be useful, too: http://mysharepointwork.blogspot.com/2009/10/sharepoint-web-services-get-choice.html
There is actually another way of getting the values using Xelements
using (var service = new SharePoint.Services.ListsSoapClient())
{
service.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var listName = "MyList";
var xelement = service.GetList(listName);
var fieldName = "Category"; //My Field name
XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/";
var selectedField = xelement.Descendants(ns + "Fields").Elements().Where(x => x.Attribute("Name").Value == fieldName).FirstOrDefault();
if (selectedField != null)
{
var choices = selectedField.Elements(ns + "CHOICES").Elements().Where(x => x.Name == ns + "CHOICE").Select(x => x.Value).ToList();
//Do something with choices
}
}

Categories