views:

157

answers:

2

Hi All,

I have an XML file

<searchResponse requestID=“500” status=“success”>
    <pso>
        <psoID ID=“770e8400-e29b-41d4-a716-446655448549”
        targetID=“mezeoAccount”/>
        <data>
            <email>[email protected]</email>
            <quotaMeg>100</quotaMeg>
            <quotaUsed>23</quotaUsed>
            <realm>Mezeo</realm>
            <path>/san1/</path>
            <billing>user2</billing>
            <active>true</active>
            <unlocked>true</unlocked>
            <allowPublic>true</allowPublic>
            <bandwidthQuota>1000000000</bandwidthQuota>
            <billingDay>1</billingDay>
        </data>
    </pso>
</searchRequest>

and I want to extract the data into a single business object. Am I better to go

MezeoAccount mcspAccount = new MezeoAccount();
mcspAccount.PsoID = doc.Element("psoID").Attribute("ID").Value;
mcspAccount.Email = doc.Element("email").Value;
...

or build a list even though I know there is only 1 record in the file?

var psoQuery = from pso in doc.Descendants("data")
    select new MezeoAccount {
        PsoID = pso.Parent.Element("psoID").Attribute("ID").Value,
        Email = pso.Element("email").Value,
        ... };

What would people suggest would be the more correct way, or a better way even, if I missed something. Am a LINQ newbie.

Cheers, Al

+1  A: 

If you know that your xml only will contain one record of the data in mind you shouldn't create a list for it. So your first example looks fine.

A pattern I personally use is something like this:

public class MezeoAccount 
{
    public string PsoID { get; set; }
    public string Email { get; set; }

    public static MezeoAccount CreateFromXml(XmlDocument xml)
    {
        return new MezeoAccount() 
        {
            PsoID = xml.Element("psoID").Attribute("ID").Value,
            Email = doc.Element("email").Value;
        };
    }
}

//Usage
var mezeoAccount = MezeoAccount.CreateFromXml(xml);
Jesper Palm
A: 

It looks like you didn't get a working answer to this question. Assuming that there can only be one account in the XML file, I would do it like this:

using System;
using System.Linq;
using System.Xml.Linq;

public class MezeoAccount
{
    public string PsoId { get; set; }
    public string Email { get; set; }
    public int QuotaMeg { get; set; }
    // Other properties...
}

public class Program
{
    public static void Main()
    {
        XDocument doc = XDocument.Load("input.xml");
        XElement pso = doc.Element("searchResponse").Element("pso");
        XElement data = pso.Element("data");
        MezeoAccount x = new MezeoAccount
        {
            PsoId = pso.Element("psoID").Attribute("ID").Value,
            Email = data.Element("email").Value,
            QuotaMeg = int.Parse(data.Element("quotaMeg").Value),
            // Other properties...
        };
    }
}
Mark Byers