How to Search Within a XMl file based on Attributes values... - c#

I am using an xml file from this link..
http://www.goalserve.com/samples/soccer_livescore.xml
..
Lets say "category" is our "Tournament" then
I need to search and show the ---
1. The listing of all the "Tournaments" in gridview or datalist.
2. The listing of matches within a selected "Tournament"..
3. The listing of events within the matches etc..
Pls guide me how to achieve this... M using a Dataset.Readxml but then the inner linking of fields become very complex...
Pls guide...
Thanks..n..regards,

The simplest way to do this is with LINQ to XML. Something like this:
var doc = XDocument.Load(url);
var tournaments = doc.Root
.Elements("category")
.Where(x => (string) x.Attribute("name") == "Tournament")
.Single(); // Is there only one matching catgeory?
var matches = tournaments
.Elements("match")
.Select(m => new
{
LocalTeam = (string) m.Element("localteam").Attribute("name"),
VisitorTeam = (string) m.Element("localteam").Attribute("name"),
Events = m.Elements("Events")
.Select(e => new
{
Player = (string) e.Attribute("player"),
Type = (string) e.Attribute("type"),
// etc
})
.ToList();
});
How you display that is then up to you. You may want to create your own "normal" types for Event, Match etc rather than using the anonymous types above.
LINQ to XML is by far the simplest way of working with XML that I've used.

Related

Simple code to get specific item from a list

I have a list of a tags. I want to get an a tag which contains a string.
I used the below code and everything work fine.
string mainLink = "";
List<HtmlNode> dlLink = new List<HtmlNode>();
dlLink = doc.DocumentNode.SelectNodes("//div[#class='links']//a").ToList();
foreach (var item in dlLink) {
if (item.Attributes["href"].Value.Contains("prefile"))
{
mainLink = item.Attributes["href"].Value;
}
}
but I want to write a simple code
var dlLink = doc.DocumentNode.SelectNodes("//div[#class='link']//a").ToList().Where(x => x.Attributes["href"].Value.Contains("prefile")).ToList().ToString();
But it does not work and I get nothing.
Your foreach is setting mainLink string, but your linq chain is using ToString on a List result.
Converting your code, you will have something like this:
mainLink = doc.DocumentNode.SelectNodes("//div[#class='links']//a")
.Where(item => item.Attributes["href"].Value.Contains("prefile"))
.Select(item => item.Attributes["href"].Value)
.Last();
I used Select to get only the href values, and getting the last as your foreach did, maybe you need to validate this last step, use a LastOrDefault, First, etc.
You can also use the Last or First instead of the Where condition:
mainlink = doc.DocumentNode.SelectNodes("//div[#class='links']//a")
.Last(item => item.Attributes["href"].Value.Contains("prefile"))
.Attributes["href"].Value;

Getting all descendants of json request

I am trying to get just name field using this query. But it gives me all data from json including school, class, ect.
Is there a way to write this so i just get value of names like:
john, ken, ...
var names = obj.Descendants()
.OfType<JProperty>()
.Where(p => p.Name == "name").Values().Distinct().ToList();
Jason string:
{"items":[{"id":404,"name":"Ken":{"id":215,"neighbourhood":"Mississauga"}]
,{"id":407,"name":"John":{"id":215,"neighbourhood":"Toronto"}]
,...
It is returning me all the value under id:404 i just want name that is Ken, John
At first your json has some error to validate. The inner object has not any key!
Why you don't use jquery each structure?
var arr = [];
$.each(jsonObj.items, function(ind, val){
arr[ind] = val.name;
});

How to filter with multiple strings in c#

I'm getting list of strings from a method and split like this
string allports = getPorts(destin); // this like "MED SAU ABU KLA USE"
var vvk = allports.Split(' ');// this has now 5 objects
Now I want to filter with all above and get all data at onece. I know how to filter for one like this
var allResult = mainFaires.Where(d => d.port == "MED");
but I want to do this for all 5 objects at once and get all data at once.how can I do that.
how about
var allResult = mainFaires.Where(d => vvk.Contains(d.port));

Filter list with linq for similar items

I have a list in which I filter, according to the text input in a TextBox in Xaml. The code below filters the List stored in the results variable. The code checks if the textbox input,ie, queryString, matches the Name of any item in the results list EXACTLY. This only brings back the items from the list where the string matches the Name of a the item exactly.
var filteredItems = results.Where(
p => string.Equals(p.Name, queryString, StringComparison.OrdinalIgnoreCase));
How do I change this so that it returns the items in the list whose Name, is similar to the queryString?
To describe what I mean by Similar:
An item in the list has a Name= Smirnoff Vodka. I want it so that if "vodka" or "smirnoff" is entered in the textbox, the the item Smirnoff Vodka will be returned.
As it is with the code above, to get Smirnoff Vodka returned as a result, the exact Name "Smirnoff Vodka" would have to be entered in the textbox.
It really depends on what you mean, by saying "similar"
Options:
1) var filteredItems = results.Where( p => p.Name != null && p.Name.ToUpper().Contains(queryString.ToUpper());
2) There is also also known algorithm as "Levenshtein distance":
http://en.wikipedia.org/wiki/Levenshtein_distance
http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm
The last link contains the source code in c#. By using it you cann determine "how close" the query string to the string in your list.
Try this:
fileList.Where(item => filterList.Contains(item))
Try this:
var query = "Smirnoff Vodka";
var queryList = query.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries);
var fileList = new List<string>{"smirnoff soup", "absolut vodka", "beer"};
var result = from file in fileList
from item in queryList
where file.ToLower().Contains(item.ToLower())
select file;

All nodes in XML using Linq C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use LINQ to read all nodes from XML
I am trying to read an XML file using Linq in C# windows application. The sample of the xml string is given below.
<Root>
<Name>John Doe</Name>
<Data>FBCCF14D504B7B2DBCB5A5BDA75BD93B</Data>
<customer>true</customer>
<Accounts>1</Accounts>
<dataSet>
<Type1>Found matching records.</Type1>
<Type2>No matches found.</Type2>
<Type3>Found matching records.</Type3>
</dataSet>
</Root>
I want to display all the data inside the <dataset> tag and <datatag> i want to read <customer> tag as well.
I have created a class with members (string type, string status). Where in type i want to store the type1, 2...and in status i want to store what is inside the type node.
I am able to accomplish this but in the code i have to give
type1 = (string)row.Element("type1"),
type2=(string)row.Element("type2"),
i want to have a generic code in which i dont have to mention every type. In other words i want to read all the child nodes of tag whithout mentioning the tag name. I have spent 2 hours searching for this on google, but haven't found anything yet.
Expected output
save the information in class object (type and status).
And i want to read the customer tag so that i can know whether the person is already a customer
Any help will be very much appreciated.
Thanks
Update
According to inputs received from Raphaƫl Althaus
I have the following code:
var list = xml.Descendants("dataSet").Elements()
.Select(m => new CustomerInfo
{
Type = m.Name.LocalName,
Value = m.Value
}).ToList();
foreach (CustomerInfo item in list)
{
MessageBox.Show(item.Type+ " "+item.Value);
}
and for reading the Customer tag i have written more code.
var isCustomer = from customer in xmlDoc.Descendants("Root")
select new
{
customer = tutorial.Element("customer").Value,
}
Can i do both in one query?. Or this method is not so heavy on performance, so i can use this?
something like that ?
var q = xml.Descendants("dataSet").Elements()
.Select(m => new
{
type = m.Name.LocalName,
value = m.Value
}).ToList();
You can also directly populate a list of your "class with members"
var list = xml.Descendants("dataSet").Elements()
.Select(m => new <TheNameOfYourClass>
{
Type = m.Name.LocalName,
Value = m.Value
}).ToList();
EDIT :
to get the "customer" value, I would do another query
var customerElement = xml.Element("customer");
var isCustomer = customerElement != null && customerElement.Value == "true";
So you could mix all of that it in a little function
public IList<YourClass> ParseCustomers(string xmlPath, out isCustomer) {
var xml = XElement.Load(xmlPath);
var customerElement = xml.Element("customer");
isCustomer = customerElement != null && customerElement.Value == "true";
return xml.Descendants("dataSet").Elements()
.Select(m => new <YourClass>
{
Type = m.Name.LocalName,
Value = m.Value
}).ToList();
}

Categories

Resources