1

我正在尝试序列化包含由 id 属性标识的“字段”元素中的数据的 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 来实现这一点?

4

3 回答 3

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

Users 集合中获取 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))))));
于 2013-03-18T20:48:14.427 回答
0

You could put an xslt style sheet in between. Serialize and deserialize with attributes to "normal" XML and from there transform to the desired form.

于 2013-03-18T21:21:24.523 回答
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"]);
于 2013-03-18T20:57:27.343 回答