Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

c# - How to load XML data to a data structure?

I have the following XML document

<?xml version = "1.0" encoding = "utf-8"?>
<flights_for_sale>
  <ad id="0001" createdon ="11/02/20" expireson="12/02/20">
    <aircraft id="A10">
      <year> 1977 </year>
      <make> <![CDATA[&c;]]> </make>
      <model> Skyhawk </model>
      <color> Light blue and white </color>
      <description>
        New paint, nearly new interior,
        685 hours SMOH, full IFR King avionics
      </description>
      <price> 23,495 </price>      
    </aircraft>
    <seller id = "s001"  phone="123-123-123"> Skyway Aircraft </seller>
    <seller id = "s002"  phone="123-123-222"> Boeing </seller>
    <seller id = "s003"  phone="123-123-233"> McDouglas </seller>
    <membership id="1000" from="12/03/16" to="12/03/18" no="M0001">Silver</membership>
    <membership id="1000" from="12/03/16" to="12/03/18" no="M0002">Gold</membership>
    <membership id="1000" from="12/03/16" to="12/03/18" no="M0003">Platinum</membership>
    <location>
      <city> Rapid City, </city>
      <state> South Dakota </state>
    </location>
  </ad>
  <ad id="002" createdon ="11/05/20" expireson="12/05/20">
    <aircraft>
      <year> 1965 </year>
      <make> &amp;p; </make>
      <model> Cherokee </model>
      <color> Gold </color>
      <description>
        240 hours SMOH, dual NAVCOMs, DME,
        new Cleveland brakes, great shape
      </description>
    </aircraft>
    <seller phone="555-333-2222"  email="jseller@www.axl.com" id="s004">John Seller</seller>
    <membership id="1000" from="12/03/16" to="12/03/18" no="M0020">State Membership</membership>
    <membership id="1000" from="12/03/16" to="12/03/18" no="M0002">Gold</membership>
    <location>
      <city> St. Joseph, </city>
      <state> Missouri </state>
    </location>
  </ad>
</flights_for_sale>

I have the following C# classes

    class Advert2
    {
        public int? Id { get; set; }
        public DateTime? CreatedOn { get; set; }
        public DateTime? ExpiresOn { get; set; }
        public Aircraft MyAircraft { get; set; }
        public List<Seller2> MySellers { get; set; }
        public List<Membership> MyMemberships { get; set; }

        public Advert2()
        {
            MySellers = new List<Seller2>();
            MyMemberships = new List<Membership>();
            MyAircraft = new Aircraft();
        }


    }

    class Seller2
    {
        public int? Id { get; set; }
        public string SellerName { get; set; }
        public string Phone { get; set; }
    }

    class Membership
    {
        public int? Id { get; set; }
        public string MembershipNumber { get; set; }

        public DateTime? From { get; set; }

        public DateTime? To { get; set; }

        public String MemberType { get; set; }

    }

    class Aircraft {

        public string Make { get; set; }
        public string Model { get; set; }


        public decimal? Price { get; set; }

        public string Description { get; set; }
    }

Then i have used the following two methods to parse XML elements and attributes ( check for NULLs )

    public static class XMLCommons
    {
        
        public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null)
        {
            var foundEl = parentEl.Element(elementName);

            if (foundEl != null)
            {
                return foundEl.Value;
            }

            return defaultValue;
        }



        public static string TryGetAttribtueValue(this XElement parentEl, string elementName, string attrName, string defaultValue = null)
        {
            var foundEl = parentEl.Element(elementName);

            if (foundEl != null) {
                //check attribute exists 

                var foundAttr = foundEl.Attribute(attrName);
                if (foundAttr != null)
                {
                    return foundAttr.Value;
                }
                
            
            }

            return defaultValue;
        }


    }

Then i have written the following code to read element/attributes on the XML, and populate data to the Advert2 object structure

            var xmlPath2 = System.IO.Path.Combine("../../../data/" + "XMLFile2.xml");
            var xml2 = XDocument.Load(xmlPath2);
          var query2 = xml2.Root.Descendants("ad").Select(n => new Advert2 { 
                    Id = Convert.ToInt32(n.Parent.TryGetAttribtueValue("ad", "id")),
                    CreatedOn = Convert.ToDateTime( n.Parent.TryGetAttribtueValue("ad", "createdon") ),
                    ExpiresOn = Convert.ToDateTime(n.Parent.TryGetAttribtueValue("ad", "expireson")),
                    MyAircraft = new Aircraft {  
                        Make = n.TryGetElementValue("make"), 
                        Model = n.TryGetElementValue("model"), 
                        Description = n.TryGetElementValue("description"), 
                        Price = Convert.ToDecimal( n.TryGetElementValue("price") ) },
                    MySellers = new List<Seller2>().Add( new Seller2 {
                                                                        Id =  Convert.ToInt32( n.TryGetAttribtueValue("seller","id") ), 
                                                                        SellerName = n.TryGetElementValue("seller"),
                                                                        Phone = n.TryGetAttribtueValue("seller","phone")
                                                                        } )   
            }).ToList();

but the issues is i get syntax errors when i tried to create objects to populate MySellers List.

Error:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0029  Cannot implicitly convert type 'void' to System.Collections.Generic.List<XMLParsing.Seller2>'   

So it seems like i don't know how to populate those two collections MySellers and MyMemberships.

is there away to populate those two collections so i can create the Averts2 Collection?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...