【问题标题】:Deserializing a string into an xml when a child element name is dynamic当子元素名称为动态时,将字符串反序列化为 xml
【发布时间】:2017-08-27 12:30:33
【问题描述】:

我有以下字符串,代表一个 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);

我需要改变什么才能得到我需要的东西?

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      相关资源
      最近更新 更多