Xml反序列化

XML的反序列化可在类的属性上标记特性来隐射反序列化。例如这种形式

public class PaymentAccount
    {
        [XmlAttribute("name")]
        public string Name
        { get; set; }

        [XmlAttribute("environment")]
        public string Environment
        { get; set; }

        [XmlElement("webServiceUrl")]
        public string WebServiceUrl
        {
            get;
            set;
        }

        [XmlElement("websiteUrl")]
        public string WebUrl
        {
            get;
            set;
        }

        [XmlArray("paymentTypes")]
        [XmlArrayItem("paymentType", typeof(PaymentType))]
        public List<PaymentType> PaymentTypes { get; set; }
    }

也可以实现IXmlSerializable来实现自定义的序列化和反序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace MvcTest
{
    [XmlRoot("siteMap", Namespace = nameSpace)]
    public class SiteMapConfig:IXmlSerializable
    {
        private const string nameSpace = "urn:schemas-test-com:sitemap";

        public static SiteMapConfig Instance
        {
            get
            {
                SiteMapConfig cg = null;
                string path = HttpContext.Current.Server.MapPath("~/config/sitemap.config");
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(SiteMapConfig));
                    object obj=xs.Deserialize(fs);
                    cg = (SiteMapConfig)obj;
                }
                return cg;
            }
        }

        public SiteMapNode ParentNode { get; set; }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            XmlNamespaceManager xn = new XmlNamespaceManager(doc.NameTable);
            xn.AddNamespace("sm", nameSpace);
            XmlNode pNode = doc.SelectSingleNode("/sm:siteMap/sm:siteMapNode",xn);
            ParentNode = new SiteMapNode() {
                Children=new List<SiteMapNode>(),
                Description = pNode.Attributes["description"].Value,
                Title=pNode.Attributes["title"].Value,
                Url = pNode.Attributes["url"].Value
            };
            XmlNodeList list = pNode.ChildNodes;
            ReadNodes(ParentNode, list);
        }

        private void ReadNodes(SiteMapNode pNode, XmlNodeList nList)
        {
            if (nList==null || nList.Count == 0)
            {
                return;
            }
            pNode.Children = new List<SiteMapNode>();
            foreach (XmlNode node in nList)
            {
                SiteMapNode sNode=new SiteMapNode() {
                    Parent=pNode,
                    Description = node.Attributes["description"].Value,
                    Title = node.Attributes["title"].Value,
                    Url = node.Attributes["url"].Value
                };
                pNode.Children.Add(sNode);
                ReadNodes(sNode, node.ChildNodes);
            }
        }

        public void WriteXml(XmlWriter writer)
        {

        }
    }

    public class SiteMapNode
    {
        public SiteMapNode Parent { get; set; }

        public string Url { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public List<SiteMapNode> Children { get; set; }
    }
}

XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="urn:schemas-test-com:sitemap" >
  <siteMapNode url="" title="p1"  description="">
    <siteMapNode url="" title="c1"  description="" />
    <siteMapNode url="" title="c2"  description="" />
  </siteMapNode>
</siteMap>
时间: 2025-01-04 02:02:42

Xml反序列化的相关文章

XML反序列化出错,XML 文档(2, 2)中有错误,不应有 &lt;configuration xmlns=&#39;&#39;&gt;

其实这个是很简单的,因为一般来说都是XML文档书写错误的问题! 只要把你想反序列化的对象,再序列化为XML文档.之后再对比之前出错的XML文档对比,就知道错误在哪了! 1 private void SerializeObject(string Xmlname) 2 { 3 XmlSerializer ser = new XmlSerializer(typeof(对象类型)); 4 5 TextWriter writer = new StreamWriter(Xmlname); 6 ser.Ser

用XmlSerializer进行xml反序列化的时候,程序报错: 不应有 &lt;xml xmlns=&#39;&#39;&gt;

原因 一,类型错误: 比如xml本来是UserInfo类型 用XmlSerializer进行反序列化传入的类型是MemberInfo这就会报错 二,xml根节点和对象的类名不一致,而又没有对类加入[XmlRoot(Namespace = "",IsNullable = false,ElementName = "RequestResult")]限制 用XmlSerializer进行xml反序列化的时候,程序报错: 不应有 <xml xmlns=''>

[C# | XML] XML 反序列化解析错误:&lt;xml xmlns=&#39;&#39;&gt; was not expected. 附通用XML到类解析方法

使用 XML 反化时出现错误: public static TResult GetObjectFromXml<TResult>(string xmlString) { TResult result; XmlSerializer serializer = new XmlSerializer(typeof(TResult), new XmlRootAttribute("xml")); using (TextReader tr = new StringReader(xmlStri

c#中对XML反序列化

生成对象类 可以手动生成. 也可以使用windows系统自带的xsd.exe工具. 根据不同的windows版本,该工具可能在: C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.7.2 Tools C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.7.2 Tools C:\Program Files (x86)\Microsoft SDKs

Code-Serialization:Xml序列化与Xml反序列化

ylbtech-Code-Serialization:Xml序列化与Xml反序列化 1.返回顶部 1. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; namespace Framework.Core { /// <summary> /// Xml序列化与反序列化 /// &

包含命名空间的xml反序列化 (1.7环境下)

需要引用 1. <!-- 1.7环境下处理带命名空间的xml BEGIN -->        <dependency>            <groupId>com.sun.xml.bind</groupId>            <artifactId>jaxb-core</artifactId>            <version>${jaxb.version}</version>        

java中xml反序列化,绑定到实体上

实体类 @XStreamAlias("ROOT") public class VehiclePassInfo { @Id @GeneratedValue(generator = "JDBC") private Integer id; @XStreamAlias("LICENSEKEY") private String licensekey; @XStreamAlias("KKBH") private String interc

1 .net将xml反序列化

public static T XmlToObject<T>(string str) where T : class { using (Stream stream = new MemoryStream()) { byte[] data = System.Text.Encoding.UTF8.GetBytes(str); stream.Write(data, 0, data.Length); stream.Position = 0; DataContractSerializer deserial

C#学习日志 day8 -------------- async await 异步方法入门(引用博客)以及序列化和反序列化的XML及json实现

首先是异步方法的介绍,这里引用自http://www.cnblogs.com/LoveJenny/archive/2011/11/01/2230933.html async and await 简单的入门 如果有几个Uri,需要获取这些Uri的所有内容的长度之和,你会如何做? 很简单,使用WebClient一个一个的获取uri的内容长度,进行累加. 也就是说如果有5个Uri,请求的时间分别是:1s 2s 3s 4s 5s. 那么需要的时间是:1+2+3+4+5=(6*5)/2=15. 如果采用并