当子元素名称是动态时,将字符串反序列化为xml

时间:2017-08-27 12:30:34

标签: c# xml serialization

我有以下字符串,表示xml层次结构:

 "<cookie page=\"1\">
    <pz_requestid last=\"{987A23F4-8582-E711-8114-005056B74623}\" first=\"{9F2E4A8C-EB7D-E711-8116-005056B71CCD}\" />
 </cookie>";

我需要将它反序列化为一个类。

我的问题是子元素可以有不同的名称。例如,在上面的例子中,它的名字是“pz_requestid”,但它可以是其他东西,比如“pz_accountid”。我不知道的是如何以一种能够正确地对其进行去序列化的方式构建类层次结构。

目前,我已经创建了以下类,仅当元素名称为pz_requestid时才有效:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class cookie
{
    public entityidfieldid pz_requestid { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public int page { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class entityidfieldid 
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string last {get; set;}

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string first { get; set; }
}

以及以下反序列化代码有效:

string inputString = "<cookie page=\"1\"><pz_requestid last=\"{987A23F4-8582-E711-8114-005056B74623}\" first=\"{9F2E4A8C-EB7D-E711-8116-005056B71CCD}\" /></cookie>";
XmlSerializer serializer = new XmlSerializer(typeof(cookie));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
cookie mycookie = (cookie)serializer.Deserialize(memStream);

我需要改变什么来获得我需要的东西?

1 个答案:

答案 0 :(得分:0)

使用xml linq非常简单

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = 
                "<cookie page=\"1\">" + 
                "<pz_requestid last=\"{987A23F4-8582-E711-8114-005056B74623}\" first=\"{9F2E4A8C-EB7D-E711-8116-005056B71CCD}\" />" +
                "</cookie>";

            XDocument doc = XDocument.Parse(xml);

            Entityidfieldid entityidfieldid = doc.Descendants("cookie").Elements().Select(x => new Entityidfieldid() {
                name = x.Name.LocalName,
                last = (string)x.Attribute("last"),
                first = (string)x.Attribute("first")
            }).FirstOrDefault();
        }
    }
    public partial class Entityidfieldid
    {
        public string name { get; set; }
        public string last { get; set; }
        public string first { get; set; }
    }
}