简体   繁体   中英

Select the value of a attribute based on another attribute value from XML

I have a xmlNodeList as

<Fields>
  <Field FieldId="1" Value="123" FieldTitle="id" FieldType="Text"/>
  <Field FieldId="2" Value="abc" FieldTitle="First Name" FieldType="Text"/>
  <Field FieldId="3" Value="efg" FieldTitle="Last Name" FieldType="Text"/>
</Fields>

now what I want is

var id        = 123   //select the `value` if `FieldId == "1";
var firstName = abc   //select the `value` if `FieldId == "2";
var last name = efg  //select the `value` if `FieldId == "3";

Edit: I don't want to loop threw the fields and check every field with if condition.

One liner solution is most welcome.

NOTE: I am dealing with very large XML and the Fields is a part of single node and there are about 500 fields of thousand of nodes, any other better solution to convert this much larger XML file into insert queries is most welcome

You can have fairly good idea, how to get it done by using this piece of code:

XDocument doc = XDocument.Load(@"XmlFile1.xml");
var elem = doc.Descendants("Field");

var id = elem.Where(c => c.Attribute("FieldId").Value.Equals("1")).Select(s => s.Attribute("Value").Value).FirstOrDefault();
var firstName = elem.Where(c => c.Attribute("FieldId").Value.Equals("2")).Select(s => s.Attribute("Value").Value).FirstOrDefault();
var lastName = elem.Where(c => c.Attribute("FieldId").Value.Equals("3")).Select(s => s.Attribute("Value").Value).FirstOrDefault();

One liner solution is not really possible as there is no way to segregate data between id, firstName, and lastName in one line of code.

ADDED:

var result = doc.Descendants("Field").Select(s => new { Field = s.Parent.GetHashCode(), FieldId = s.Attribute("FieldId").Value, Value = s.Attribute("Value").Value });
foreach (var val in result.GroupBy(g => g.Field).Select(s => s))
{
    var id = result.Where(c => c.Field == val.Key && c.FieldId == "1").Select(s => s.Value).FirstOrDefault();
    var firstName = result.Where(c => c.Field == val.Key && c.FieldId == "2").Select(s => s.Value).FirstOrDefault();
    var lastName = result.Where(c => c.Field == val.Key && c.FieldId == "3").Select(s => s.Value).FirstOrDefault();
    // ... do something ...
}

Hope this newly added code would give you some better idea :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM