LINQ XML将不同的层次结构读入1个对象

时间:2010-02-02 21:38:40

标签: c# linq-to-xml

我有一个XML文件

<searchResponse requestID=“500” status=“success”>
    <pso>
        <psoID ID=“770e8400-e29b-41d4-a716-446655448549”
        targetID=“mezeoAccount”/>
        <data>
            <email>user2@example.net</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>

我想将数据提取到一个业务对象中。我最好去吗

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

或建立一个列表,即使我知道文件中只有1条记录?

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

如果我错过了什么,人们会建议更正确的方式,或者更好的方式。

2 个答案:

答案 0 :(得分:1)

如果您知道您的xml仅包含一条数据记录,则不应为其创建列表。所以你的第一个例子看起来很好。

我个人使用的模式是这样的:

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);

答案 1 :(得分:0)

看起来你没有得到这个问题的工作答案。假设XML文件中只能有一个帐户,我会这样做:

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...
        };
    }
}