Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 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="[email protected]" 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:

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?

question from:https://stackoverflow.com/questions/65856219/how-to-load-xml-data-to-a-data-structure

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

1 Answer

0 votes
by (71.8m points)

I know this is not quite in the spirit of the question. However, it should be as simple as

var xmlStream = new StreamReader(@"D:something.xml");
var serializer = new XmlSerializer(typeof(flights_for_sale));
var result = (flights_for_sale)serializer.Deserialize(xmlStream);

The below was obtained by pasting the xml into visual studio

Edit ?? Paste Special ?? Paste XML as Classes

// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class flights_for_sale
{

   private flights_for_saleAD[] adField;

   /// <remarks/>
   [System.Xml.Serialization.XmlElementAttribute("ad")]
   public flights_for_saleAD[] ad
   {
      get
      {
         return this.adField;
      }
      set
      {
         this.adField = value;
      }
   }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleAD
{

   private flights_for_saleADAircraft aircraftField;

   private flights_for_saleADSeller[] sellerField;

   private flights_for_saleADMembership[] membershipField;

   private flights_for_saleADLocation locationField;

   private byte idField;

   private string createdonField;

   private string expiresonField;

   /// <remarks/>
   public flights_for_saleADAircraft aircraft
   {
      get
      {
         return this.aircraftField;
      }
      set
      {
         this.aircraftField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlElementAttribute("seller")]
   public flights_for_saleADSeller[] seller
   {
      get
      {
         return this.sellerField;
      }
      set
      {
         this.sellerField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlElementAttribute("membership")]
   public flights_for_saleADMembership[] membership
   {
      get
      {
         return this.membershipField;
      }
      set
      {
         this.membershipField = value;
      }
   }

   /// <remarks/>
   public flights_for_saleADLocation location
   {
      get
      {
         return this.locationField;
      }
      set
      {
         this.locationField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public byte id
   {
      get
      {
         return this.idField;
      }
      set
      {
         this.idField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string createdon
   {
      get
      {
         return this.createdonField;
      }
      set
      {
         this.createdonField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string expireson
   {
      get
      {
         return this.expiresonField;
      }
      set
      {
         this.expiresonField = value;
      }
   }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADAircraft
{

   private ushort yearField;

   private string makeField;

   private string modelField;

   private string colorField;

   private string descriptionField;

   private string priceField;

   private string idField;

   /// <remarks/>
   public ushort year
   {
      get
      {
         return this.yearField;
      }
      set
      {
         this.yearField = value;
      }
   }

   /// <remarks/>
   public string make
   {
      get
      {
         return this.makeField;
      }
      set
      {
         this.makeField = value;
      }
   }

   /// <remarks/>
   public string model
   {
      get
      {
         return this.modelField;
      }
      set
      {
         this.modelField = value;
      }
   }

   /// <remarks/>
   public string color
   {
      get
      {
         return this.colorField;
      }
      set
      {
         this.colorField = value;
      }
   }

   /// <remarks/>
   public string description
   {
      get
      {
         return this.descriptionField;
      }
      set
      {
         this.descriptionField = value;
      }
   }

   /// <remarks/>
   public string price
   {
      get
      {
         return this.priceField;
      }
      set
      {
         this.priceField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string id
   {
      get
      {
         return this.idField;
      }
      set
      {
         this.idField = value;
      }
   }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADSeller
{

   private string idField;

   private string phoneField;

   private string emailField;

   private string valueField;

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string id
   {
      get
      {
         return this.idField;
      }
      set
      {
         this.idField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string phone
   {
      get
      {
         return this.phoneField;
      }
      set
      {
         this.phoneField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string email
   {
      get
      {
         return this.emailField;
      }
      set
      {
         this.emailField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlTextAttribute()]
   public string Value
   {
      get
      {
         return this.valueField;
      }
      set
      {
         this.valueField = value;
      }
   }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADMembership
{

   private ushort idField;

   private string fromField;

   private string toField;

   private string noField;

   private string valueField;

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public ushort id
   {
      get
      {
         return this.idField;
      }
      set
      {
         this.idField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string from
   {
      get
      {
         return this.fromField;
      }
      set
      {
         this.fromField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string to
   {
      get
      {
         return this.toField;
      }
      set
      {
         this.toField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlAttributeAttribute()]
   public string no
   {
      get
      {
         return this.noField;
      }
      set
      {
         this.noField = value;
      }
   }

   /// <remarks/>
   [System.Xml.Serialization.XmlTextAttribute()]
   public string Value
   {
      get
      {
         return this.valueField;
      }
      set
      {
         this.valueField = value;
      }
   }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADLocation
{

   private string cityField;

   private string stateField;

   /// <remarks/>
   public string city
   {
      get
      {
         return this.cityField;
      }
      set
      {
         this.cityField = value;
      }
   }

   /// <remarks/>
   public string state
   {
      get
      {
         return this.stateField;
      }
      set
      {
         this.stateField = value;
      }
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...