简体   繁体   中英

How to fetch conditional Deserialization xml list in c#

I want to fetch data from deserialize xml list with some condition. But I did not get any proper solution for that. Below is my code snippet:

 public List<LinkInfo> GetLinks(string entityType, string relatedEntityType, string linkType)
    {
        try
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(Project));
            TextReader reader = new StreamReader(@"E:\\SampleMetaData.xml");
            object obj = deserializer.Deserialize(reader);

            Project xmlData = (Project)obj;
            return xmlData.Module.Links.Link.Select(field => new LinkInfo
            {
                EntityId = field.EntityId,
                EntityType = field.EntityType,
                RelatedEntityId = field.RelatedEntityId,
                RelatedEntityType = field.RelatedEntityType,
                LinkType = field.LinkType
            }).ToList();             
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error in",ex);
            throw;
        }
       
    }

Below is my XML file format:

    <Links>
        <Link EntityId="5" EntityType="Doors_Module1"  RelatedEntityId="7" RelatedEntityType="Doors_Module2" LinkType="InLink"/>
        <Link EntityId="6" EntityType="Doors_Module1"  RelatedEntityId="8" RelatedEntityType="Doors_Module2" LinkType="InLink"/>
        <Link EntityId="7" EntityType="Doors_Module1"  RelatedEntityId="9" RelatedEntityType="Doors_Module2" LinkType="External"/>
    </Links>

I want to fetch like where LinkType="Inlink" EntityType="Doors_Module1" and RelatedEntityType="Doors_Module2"

How can I do this?

return xmlData.Module.Links.Link
.Where(x=>.LinkType == 'Inlink' && x.EntityType == 'Doors_Module1')
.Select(field => new LinkInfo
        {
            EntityId = field.EntityId,
            EntityType = field.EntityType,
            RelatedEntityId = field.RelatedEntityId,
            RelatedEntityType = field.RelatedEntityType,
            LinkType = field.LinkType
        }).ToList();     

This code should work for you

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