使用属性标识的数据序列化XML

时间:2013-03-18 20:44:20

标签: c# .net xml xml-serialization

我正在尝试序列化包含由id属性标识的'field'元素内的数据的XML:

<data>
  <row>
   <field id="firstName">Stef</field>
   <field id="lastName">Ben</field>
   <field id="city">LA</field>
   <field id="state">CA</field>
  </row>
  <row>
   <field id="firstName">Ann</field>
   <field id="lastName">Brown</field>
   <field id="city">NY</field>
   <field id="state">NY</field>
  </row>
</data>

我的目标是创建一个如下所示的类:

class User
{
    private string firstName;
    [XmlElement("firstName")]
    public string FirstName { get; set; }     
    [XmlElement("lastName")]
    public string LastName { get; set; }
    [XmlElement("city")]
    public string City { get; set; }
    [XmlElement("state")]
    public string State { get; set; }
}

您对如何序列化和反序列化此XML有任何想法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用LINQ to XML查询XML:

var doc = XDocument.Load("Input.txt");
var users = doc.Root.Elements("row")
                    .Select(r => new User
                    {
                        FirstName = (string)r.Elements("field")
                                             .Single(f => (string)f.Attribute("id") == "firstName"),
                        LastName = (string)r.Elements("field")
                                            .Single(f => (string)f.Attribute("id") == "lastName"),
                        City = (string)r.Elements("field")
                                        .Single(f => (string)f.Attribute("id") == "city"),
                        State = (string)r.Elements("field")
                                         .Single(f => (string)f.Attribute("id") == "state"),
                    }).ToList();

User s:

的集合中获取XML
var dox = new XDocument(new XElement("data",
                (from u in users
                select new XElement("row",
                    new XElement("field",
                        new XAttribute("id", "firstName"),
                        new XText(u.FirstName)),
                    new XElement("field",
                        new XAttribute("id", "lastName"),
                        new XText(u.LastName)),
                    new XElement("field",
                        new XAttribute("id", "city"),
                        new XText(u.City)),
                    new XElement("field",
                        new XAttribute("id", "state"),
                        new XText(u.State))))));

答案 1 :(得分:0)

如何使用Linq并创建词典列表

var xDoc = XDocument.Parse(xml); //XDocument.Load(filename);
var rows = xDoc.Descendants("row")
               .Select(r => r.Elements()
                             .ToDictionary(f=>f.Attribute("id").Value,f=>f.Value))
               .ToList();

Console.WriteLine(rows[0]["firstName"]);

答案 2 :(得分:0)

您可以在其间放置一个xslt样式表。使用“普通”XML的属性进行序列化和反序列化,然后从那里转换为所需的形式。