XML序列化返回null

时间:2016-06-23 19:15:16

标签: c# xml xml-serialization

我想获得" U8"中的信息(名称和Val)。我从文本文件中获取的以下XML字符串的节点。

<Cluster>   
    <String>
        <Name>SomeNAme</Name>
        <Val>
            &lt;Cluster&gt;
                &lt;Name&gt;SomeNAme&lt;/Name&gt;
                &lt;NumElts&gt;2&lt;/NumElts&gt;
                &lt;U8&gt;
                    &lt;Name&gt;SomeNAme&lt;/Name&gt;
                    &lt;Val&gt;11&lt;/Val&gt;
                &lt;/U8&gt;
                &lt;U8&gt;
                    &lt;Name&gt;SomeNAme&lt;/Name&gt;
                    &lt;Val&gt;208&lt;/Val&gt;
                &lt;/U8&gt;
            &lt;/Cluster&gt;
        </Val>
    </String>
</Cluster>

我写了以下内容以获取属于U8节点的信息,但输出返回Null。我做错了什么?感谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Xml.Linq;
using System.Xml;
namespace testXMLSerializer
{
    class Class4
    {
        static void Main(string[] args)
        {
            var xml = File.ReadAllText(@"C:\test.xml");

            XmlSerializer serializer = new XmlSerializer(typeof(Cluster));

            using (var reader = new StringReader(xml))
            {
                var info = (Cluster)serializer.Deserialize(reader);
            }

            Console.Read();
        }
    }

    [XmlRoot("Cluster")]
    public class Cluster
    {
        [XmlElement("String")]
        public List<Cluster_String> Cluster_String { get; set; } // I'll have many of this items in the actual xml
    }

    public class Cluster_String
    {
        [XmlElement("Val")]
        public Val Val { get; set; }
    }

    public class Val
    {
        [XmlElement("Cluster")]
        public Cluster_S_V_Cluster Cluster_S_V_Cluster { get; set; }
    }

    public class Cluster_S_V_Cluster
    {
        [XmlElement("U8")]
        public List<U8> U8 { get; set; }
    }

    public class U8
    {
        public string Name { get; set; }
        public string Val { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是内部群集节点是编码的。 如果你不能在第一个地方(在保存文件时)在该文件中解码它,只需添加:

 xml = System.Net.WebUtility.HtmlDecode(xml);

之后:

 var xml = File.ReadAllText(@"C:\test.xml");

你的主要应该看起来像这样:

 static void Main(string[] args)
    {
        var xml = File.ReadAllText(@"test.xml");
        xml = System.Net.WebUtility.HtmlDecode(xml);
        XmlSerializer serializer = new XmlSerializer(typeof(Cluster));

        using (var reader = new StringReader(xml))
        {
            var info = (Cluster)serializer.Deserialize(reader);
        }

        Console.Read();
    }