How do I read Child Nodes in Xml file using MVC - c#

## XML FİLE ##
<Title month="1" year="2016">
<film day="1">
<morning>
Fight Club
</morning>
<night>
Inceptıon
</night>
</film>
<film day="2">
<morning>
xyzasda
</morning>
<night>
czxsadasas
</night>
</film>
</Title>
MY CLASS
public class FilmController : Controller
{
public ActionResult DisplayXML()
{
var data = new List<Films>();
data = ReturnData();
return View(data);
}
private List<Films> ReturnData(){
string xmldata = "myxmldata.xml";
DataSet ds = new DataSet();
ds.ReadXml(xmldata);
var filmlist= new List<Films>();
filmlist= (from rows in ds.Tables[0].AsEnumerable()
select new Films
{
month= Convert.ToInt32(rows[0].ToString()),
year= rows[1].ToString(),
film= rows[2].ToString(),
morning= rows[3].ToString(),
night= rows[4].ToString(),
}).ToList();
return filmlist;
}
}
Model
public int month{ get; set; }
public string year{ get; set; }
public string day { get; set; }
public string morning { get; set; }
public string night{ get; set; }
How to read child node? I want to create a table. I will create a table using this data. I want to keep it on a list.
I edited..
Error: Additional information: Cannot find column 3.
where is the error? I want to read the xml file.

You can parse your XML with the following:
var xml = XDocument.Load(xmlFile);
var films = xml.Descendants("film").Select(d => new Films()
{
month = Convert.ToInt32(d.Parent.Attribute("month").Value),
year = d.Parent.Attribute("year").Value,
day = d.Attribute("day").Value,
morning = d.Element("morning").Value,
night = d.Element("night").Value
});
See it in action HERE.

You can retrieve Films collection using Linq-To-XML easily like this:
XDocument xdoc = XDocument.Load(xmldata);
List<Films> result = xdoc.Descendants("film")
.Select(x =>
{
var film = x;
var title = x.Parent;
return new Film
{
month = (int)title.Attribute("month"),
year = (string)title.Attribute("year"),
day = (string)film.Attribute("day"),
morning = (string)film.Element("morning"),
night = (string)film.Element("night")
};
}
).ToList();
This will return two films, and each will have month & year based on Title node.
Code Explanation:
First we are finding all the film nodes, then projecting it using Select. In the select clause we can save variable for each film (you can think of film inside select method like alias in foreach loop). Also, we are storing the parent Title node in title variable. After this all we need to do is read the elements & attributes.
If understanding Method syntax is difficult, then here is the equivalent query syntax:
List<Films> result2 = (from x in xdoc.Descendants("film")
let film = x
let title = x.Parent
select new Film
{
month = (int)title.Attribute("month"),
year = (string)title.Attribute("year"),
day = (string)film.Attribute("day"),
morning = (string)film.Element("morning"),
night = (string)film.Element("night")
}).ToList();
Working Fiddle

When i read your xml in a dataset i get 2 tables
Table 1 "Title" with one row and 3 columns
Table 2 "film" with two rows and 4 columns
you read on Tables[0] (3 columns) - and you try to read 4th column of 3..
you need to change your loop - since you need to load Data from two tables.

Related

Given a list of several of the same object, group and combine them based on field value

Sorry for the incoherent title. I don't know how to concisely explain my problem, which is why I didn't really know how to look it up. I'll explain using an example...
Let's say I have a class:
public class cas
{
public string name { get; set; }
public int num { get; set; }
}
With that class, I make several objects and stick them into a list. For the sake of example, I will make 4:
var list = new List<cas>
{
new cas { name = "firstname", num = 1 },
new cas { name = "firstname", num = 2 },
new cas { name = "lastname", num = 3 },
new cas { name = "lastname", num = 4 }
};
Is there a way to take this List and combine any objects with the same name field?
So, the new list would be 1 object with:
name = "firstname", num = 3,
name = "lastname", num = 7
There's the obvious "long" way to do it, but it would be clunky and expensive (go through the list several times to find like-objects). I was wondering if I was missing any clean way of doing it. I intentionally made a simple example so that the answer would be a proof of concept rather than writing my code for me. My actual problem is more complex than this, but I can't figure out this one aspect of it.
Using Linq, you have a GroupBy Method and a Select Method:
list = list.GroupBy(x=> x.name)
.Select(x=> new cas() { name = x.Key, num = x.Sum(y=> y.num) }).ToList();
Or using Elegant query-syntax:
list = (from item in list
group item by item.name into grouping
select new cas()
{
name = grouping.Key,
num = grouping.Sum(x => x.num)
}).ToList();
Note that to use these methods, you have to add using System.Linq at the top of your source file.
You can use linq, you would have to group them on name property and then sum on the num property of each group like:
var result = list.GroupBy(x=>x.name)
.Select(g=> new cas
{
name = g.Key,
num = g.Sum(x=>x.num)
});

How do I nest this LINQ query?

I have an XML document from a web service that I am trying to query. However, I am not sure how to query the XML when it has elements nested inside other elements.
Here is a section of the XML file (I haven't included all of it because it's a long file):
<response>
<display_location>
<full>London, United Kingdom</full>
<city>London</city>
<state/>
<state_name>United Kingdom</state_name>
<country>UK</country>
<country_iso3166>GB</country_iso3166>
<zip>00000</zip>
<magic>553</magic>
<wmo>03772</wmo>
<latitude>51.47999954</latitude>
<longitude>-0.44999999</longitude>
<elevation>24.00000000</elevation>
</display_location>
<observation_location>
<full>London,</full>
<city>London</city>
<state/>
<country>UK</country>
<country_iso3166>GB</country_iso3166>
<latitude>51.47750092</latitude>
<longitude>-0.46138901</longitude>
<elevation>79 ft</elevation>
</observation_location>
I can query "one section at a time" but I'm constructing an object from the LINQ. For example:
var data = from i in weatherResponse.Descendants("display_location")
select new Forecast
{
DisplayFullName = i.Element("full").Value
};
var data = from i in weatherResponse.Descendants("observation_location")
select new Forecast
{
ObservationFullName = i.Element("full").Value
};
And my "Forecast" class is basically just full of properties like this:
class Forecast
{
public string DisplayFullName { get; set; };
public string ObservationFullName { get; set; };
//Lots of other properties that will be set from the XML
}
However, I need to "combine" all of the LINQ together so that I can set all the properties of the object. I have read about nested LINQ but I do not know how to apply it to this particular case.
Question: How do I go about "nesting/combining" the LINQ so that I can read the XML and then set the appropriate properties with said XML?
One possible way :
var data = from i in weatherResponse.Descendants("response")
select new Forecast
{
DisplayFullName = (string)i.Element("display_location").Element("full"),
ObservationFullName = (string)i.Element("observation_location").Element("full")
};
Another way ... I prefer using the Linq extension methods in fluent style
var results = weatherResponse.Descendants()
.SelectMany(d => d.Elements())
.Where(e => e.Name == "display_location" || e.Name == "observation_location")
.Select(e =>
{
if(e.Name == "display_location")
{
return new ForeCast{ DisplayFullName = e.Element("full").Value };
}
else if(e.Name == "observation_location")
{
return new ForeCast{ ObservationFullName = e.Element("full").Value };
}
else
{
return null;
}
});

List<object> Self-Filter

I have a list like
List<VoieData> listVoieData = new List<VoieData>();
and in VoieData Class I have :
public class VoieData
{
public int Depart { set; get; }
public int Arrive { set; get; }
public int DistanceDepart { set; get; }
public int DistanceArrive { set; get; }
}
Since I have a massive values I want to only consider all my Depart number , I would like to filter the listVoieData by finding the Arrive only have the same value as the
Depart
for example I have
listVoieData.Select(p=>p.Depart).ToList()= List<int>{1,2,3};
listVoieData.Select(p=>p.Arrive).ToList()= List<int>{1,2,3,4,5};
I need to throw away the entire VoieData which contain {4,5} as Arrive
right now my soulution is like this , but it' s not correct ;
List<VoieData> listVoieDataFilter = listVoieData .Join(listVoieData , o1 => o1.Arrive, o2 => o2.Depart, (o1, o2) => o1).ToList();
Sorry for the confusing question ;
I want to remove Arrive which is different from all the Depart in the list list , and return the new
List
it 's not only in one VoieData;
Arrive!=Depart
Thanks
I think you want to remove all objects where Arrive is not in any of the Depart from any object. In that case, first get all Depart and then filter by Arrive:
HashSet<int> allDepart = new HashSet<int>(listVoieData.Select(x => x.Depart));
var result = listVoieData.Where(v => !allDepart.Contains(v.Arrive))
We use a HashSet<int> for efficiency.
Use LINQ Where:
var records = listVoieData.Where(x => x.Arrive == x.Depart);
This will return results where both Arrive and Depart are the same.
That would be a typical case to use linq.
something like:
var res = from data in listVoieData
where data.Depart == data.Arrive
select data;
and then optionally just use res.ToArray() to run the query and get the array.
Since you've stated that you want:
I want to remove Arrive which is different from all the Depart
This can be re-phrased as, "The set of all arrivals except those in the set of departures", which translates very nicely into the following LINQ query:
var arrivalsWithNoDepartures = listVoieData.Select(p=>p.Arrive)
.Except(listVoieData.Select(p=>p.Depart));

Linq: DataTable to List. Cast issue

I'm getting the Specified cast is not valid. and I can't find why. Here's my code.
Object Layer.
public class Supervisor
{
public long ID { get; set; }
public string stringField1 { get; set; }
public string stringField2 { get; set; }
public string stringField3 { get; set; }
public int intField1{ get; set; }
public int intField2 { get; set; }
}
C# Method.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetPend(string value1FromjqGrid, string value2FromjqGrid)
{
string query = "GetPend";
string supervisor = "";
Supervision _query = new Supervision();
DataTable dt = _query.GetSupervisorQuery(value1FromjqGrid, value2FromjqGrid, supervisor, query );
List<Supervisor> lines = (from dt1 in dt.AsEnumerable()
select new Supervisor()
{
ID = dt1.Field<long>("ID"),
stringField1 = dt1.Field<string>("Linea"),
intField1 = dt1.Field<int>("Tiempo"),
intField2 = dt1.Field<int>("TIPOACTIVIDAD_ID"),
stringField2 = dt1.Field<string>("ACT_ID"),
stringField3 = dt1.Field<string>("OBS")
}).ToList();
var grid = new
{
page = 1,
records = lines.Count(),
total = lines.Count(),
rows = from item in lines
select new
{
id = item.ID,
cell = new string[]{
item.stringField1,
item.intField1.ToString(),
item.intField2.ToString(),
item.stringField2,
item.stringField3
}
}
};
return JsonConvert.SerializeObject(grid);
}
That's it more or less. When the LinQ iteration starts it crashes. The DataTable is filled correctly as I've checked, and dt1 contains the fields correctly. I see the "" for the string columns and the numbers for the int's (I've done the SQL Stored Procedure myself so I did the checking there too.) With this I'm also assuring that the 2 parameters from the jqGrid are OK, but still I placed some alerts just right before the calling and yes, they are fine.
I've pasted the code it seems to be relevant since the error comes when the codes trying to parse the information from the DataTable to the List, if you'd need to check the javascript involved here just let me know but I don't think that's needed.
Clearly I'm not seeing something so hopefully you can guide me in the right direction. Thanks.
PS. I've tried to check it out at LINQPad4 but I can't give it a try since I don't know how to represent the original DataTable variable there.
Update.
This is what VS gives to me when I expand the error.:
at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
at WEB.Supervisor.<GetPend>b__b(DataRow dt1) in E:\Dev\VS\WEB\Supervisor.aspx.cs:line 110
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at WEB.Supervisor.GetPend(String value1FromjqGrid, String value2FromjqGrid) in E:\Dev\VS\WEB\Supervisor.aspx.cs:line 109
Lines 109 and 110 are these
List<Supervisor> lines = (from dt1 in dt.AsEnumerable()
select new Supervisor()
It crashes at the beggining of the convert process.
UPDATE 2
According to comments I did as follows.
Took the SELECT and turned into a SELECT INTO for generating a trash table. Then checked its design and for my honest surprise, the field CAST(ACT_ID AS NVARCHAR(50)) was still decimal and not nvarchar as I expected.
So, seems like I have to handle this in LinQ as a decimal, or could I do something else? I've tried working with decimals in the past and didn't succed.
It should be type mismatch between column type in the database and the type of data used in List<Supervisor> lines = (from dt1 in dt.AsEnumerable() select new Supervisor() {...}).ToList();.
After some conversation in comments we could see that the type of "ACT_ID" is decimal in the database. So to fix the exception problem one can do something like the following:
List<Supervisor> lines = (from dt1 in dt.AsEnumerable()
select new Supervisor {
ID = dt1.Field<long>("ID"),
stringField1 = dt1.Field<string>("Linea"),
intField1 = dt1.Field<int>("Tiempo"),
intField2 = dt1.Field<int>("TIPOACTIVIDAD_ID"),
stringField2 = dt1.Field<decimal>("ACT_ID").ToString(),
stringField3 = dt1.Field<string>("OBS")
}).ToList();

LINQ to XML: Collapse mutliple levels to single list

I'm currently working on a Silverlight app and need to convert XML data into appropriate objects to data bind to. The basic class definition for this discussion is:
public class TabularEntry
{
public string Tag { get; set; }
public string Description { get; set; }
public string Code { get; set; }
public string UseNote { get; set; }
public List<string> Excludes { get; set; }
public List<string> Includes { get; set; }
public List<string> Synonyms { get; set; }
public string Flags { get; set; }
public List<TabularEntry> SubEntries { get; set; }
}
An example of the XML that might come in to feed this object follows:
<I4 Ref="1">222.2
<DX>Prostate</DX>
<EX>
<I>adenomatous hyperplasia of prostate (600.20-600.21)</I>
<I>prostatic:
<I>adenoma (600.20-600.21)</I>
<I>enlargement (600.00-600.01)</I>
<I>hypertrophy (600.00-600.01)</I>
</I>
</EX>
<FL>M</FL>
</I4>
So, various nodes map to specific properties. The key ones for this question are the <EX> and <I> nodes. The <EX> nodes will contain a collection of one or more <I> nodes and in this example matches up to the 'Excludes' property in the above class definition.
Here comes the challenge (for me). I don't have control over the web service that emits this XML, so changing it isn't an option. You'll notice that in this example one <I> node also contains another collection of one or more <I> nodes. I'm hoping that I could use a LINQ to XML query that will allow me to consolidate both levels into a single collection and will use a character that will delimit the lower level items, so in this example, when the LINQ query returned a TablularEntry object, it would contain a collection of Exclude items that would appear as follows:
adenomatous hyperplasia of prostate
(600.20-600.21)
prostatic:
*adenoma (600.20-600.21)
*enlargement (600.00-600.01)
*hypertrophy (600.00-600.01)
So, in the XML the last 3 entries are actually child objects of the second entry, but in the object's Excludes property, they are all part of the same collection, with the former child objects containing an identifier character/string.
I have the beginnings of the LINQ query I'm using below, I can't quite figure out the bit that will consolidate the child objects for me. The code as it exists right now is:
List<TabularEntry> GetTabularEntries(XElement source)
{
List<TabularEntry> result;
result = (from tabularentry in source.Elements()
select new TabularEntry()
{
Tag = tabularentry.Name.ToString(),
Description = tabularentry.Element("DX").ToString(),
Code = tabularentry.FirstNode.ToString(),
UseNote = tabularentry.Element("UN") == null ? null : tabularentry.Element("UN").Value,
Excludes = (from i in tabularentry.Element("EX").Elements("I")
select i.Value).ToList()
}).ToList();
return result;
}
I'm thinking that I need to nest a FROM statement inside the
Excludes = (from i...)
statement to gather up the child nodes, but can't quite work it through. Of course, that may be because I'm off in the weeds a bit on my logic.
If you need more info to answer, feel free to ask.
Thanks in advance,
Steve
Try this:
List<TabularEntry> GetTabularEntries(XElement source)
{
List<TabularEntry> result;
result = (from tabularentry in source.Elements()
select new TabularEntry()
{
Tag = tabularentry.Name.ToString(),
Description = tabularentry.Element("DX").ToString(),
Code = tabularentry.FirstNode.ToString(),
UseNote = tabularentry.Element("UN") == null ? null : tabularentry.Element("UN").Value,
Excludes = (from i in tabularentry.Element("EX").Descendants("I")
select (i.Parent.Name == "I" ? "*" + i.Value : i.Value)).ToList()
}).ToList();
return result;
}
(edit)
If you need the current nested level of "I" you could do something like:
List<TabularEntry> GetTabularEntries(XElement source)
{
List<TabularEntry> result;
result = (from tabularentry in source.Elements()
select new TabularEntry()
{
Tag = tabularentry.Name.ToString(),
Description = tabularentry.Element("DX").ToString(),
Code = tabularentry.FirstNode.ToString(),
UseNote = tabularentry.Element("UN") == null ? null : tabularentry.Element("UN").Value,
Excludes = (from i in tabularentry.Element("EX").Descendants("I")
select (ElementWithPrefix(i, '*'))).ToList()
}).ToList();
return result;
}
string ElementWithPrefix(XElement element, char c)
{
string prefix = "";
for (XElement e = element.Parent; e.Name == "I"; e = e.Parent)
{
prefix += c;
}
return prefix + ExtractTextValue(element);
}
string ExtractTextValue(XElement element)
{
if (element.HasElements)
{
return element.Value.Split(new[] { '\n' })[0].Trim();
}
else
return element.Value.Trim();
}
Input:
<EX>
<I>adenomatous hyperplasia of prostate (600.20-600.21)</I>
<I>prostatic:
<I>adenoma (600.20-600.21)</I>
<I>enlargement (600.00-600.01)</I>
<I>hypertrophy (600.00-600.01)
<I>Bla1</I>
<I>Bla2
<I>BlaBla1</I>
</I>
<I>Bla3</I>
</I>
</I>
</EX>
Result:
* adenomatous hyperplasia of prostate (600.20-600.21)
* prostatic:
* *adenoma (600.20-600.21)
* *enlargement (600.00-600.01)
* *hypertrophy (600.00-600.01)
* **Bla1
* **Bla2
* ***BlaBla1
* **Bla3
Descendants will get you all of the I children. The FirstNode will help seperate the value of prostatic: from the values of its children. The there's a return character in the value of prostatic:, which I removed with Trim.
XElement x = XElement.Parse(#"
<EX>
<I>adenomatous hyperplasia of prostate (600.20-600.21)</I>
<I>prostatic:
<I>adenoma (600.20-600.21)</I>
<I>enlargement (600.00-600.01)</I>
<I>hypertrophy (600.00-600.01)</I>
</I>
</EX>");
//
List<string> result = x
.Descendants(#"I")
.Select(i => i.FirstNode.ToString().Trim())
.ToList();
Here's a hacky way to get those asterisks in. I don't have time to improve it.
List<string> result2 = x
.Descendants(#"I")
.Select(i =>
new string(Enumerable.Repeat('*', i.Ancestors(#"I").Count()).ToArray())
+ i.FirstNode.ToString().Trim())
.ToList();

Categories