反序列化XML命名空间没有,但一类期待的命名空间 [英] Deserialize XML without namespaces but in a class expecting namespaces

查看:279
本文介绍了反序列化XML命名空间没有,但一类期待的命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复:?结果
序列化对象
不一样的。我想在其他方式:反序列化

Duplicate:
Omitting all xml namespaces when serializing an object? Not the same.. I want in the other way: Deserialize!

我有一个C#类波纹管:


I have a C# class as bellow:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe")]
[System.Xml.Serialization.XmlRootAttribute("NFe", Namespace = "http://www.portalfiscal.inf.br/nfe", IsNullable = false)]
public partial class TNFe
{

    private TNFeInfNFe infNFeField;

    private SignatureType signatureField;

    /// <remarks/>
    public TNFeInfNFe infNFe
    { ...



我使用这个类来序列按用户要求/反序列化的XML文件。
,但我有一个问题:命名空间定义了这个软件的新版本中添加。
中的XML仍然是一样的,只是添加命名空间定义。

I use this class to serialize/deserialize XML files by user request. But I've got a problem: namespaces definition were added on the new version of this software. The XML is still the same, only adding namespaces definition.

例如,去年的版本...

Eg., last version...

<?xml version="1.0" encoding="utf-8" ?>
  <NFe>
    <infNFe version="1.10">
      ...

和新版本...

<?xml version="1.0" encoding="utf-8" ?> 
  <NFe xmlns="http://www.portalfiscal.inf.br/nfe">
    <infNFe version="2.10">
      ...



我需要加载使用和不使用这些命名空间的XML文件。
我有很多嵌套类和每个它有自己的命名空间定义。

I need to load XML files with and without these namespaces. I have a lot of nested classes and each of it has its own namespaces definition.

我想用相同的类为XML ,有和没有命名空间。

我试图创建一个XmlTextReader并覆盖的namespaceURI方法,但我仍收到没有太多的信息异常。我认为.NET引擎试图迫使对XML类的命名空间定义。

I tried to create an XmlTextReader and overwrite the NamespaceURI method, but I still receives an exception with no much info. I think .NET engine is trying to force the class namespace definition against the XML.

推荐答案

我已经碰到了类似的挑战,代理类。对于我不会进入的原因,我需要手动序列化类使用Web服务器上的XmlSerializer和反序列化的客户端。我没能在网上找到一个完美的解决方案,所以我只是通过从Visual Studio中后,手动我自动生成它的代理类删除XmlTypeAttribute回避的问题。

I had run into a similar challenge with a proxy class. For reasons that I won't go into, I needed to serialize the class manually using the XmlSerializer on web server and deserialize on client. I was not able to find an elegant solution online, so I just avoided the issue by removing the XmlTypeAttribute from the proxy class manually after I auto-generated it in Visual Studio.

我一直回来看看是否有一种方式来获得命名空间来锻炼。这是我如何得到它,而不需要修改自动生成的类的工作。最后我用一个XmlTextReader返回匹配属性名称节点所需的命名空间。还有改进的余地,但我希望它可以帮助别人。

I kept coming back to see if there was a way to get the namespace to workout. Here is how I got it working without the need to modify the auto-generated classes. I ended up using an XmlTextReader to return the desired namespace on nodes matching a property name. There is room for improvement, but i hope it helps someone.

class Program
{
    static void Main(string[] args)
    {
        //create list to serialize
        Person personA = new Person() { Name = "Bob", Age = 10, StartDate = DateTime.Parse("1/1/1960"), Money = 123456m };
        List<Person> listA = new List<Person>();
        for (int i = 0; i < 10; i++)
        {
            listA.Add(personA);
        }

        //serialize list to file
        XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
        XmlTextWriter writer = new XmlTextWriter("Test.xml", Encoding.UTF8);
        serializer.Serialize(writer, listA);
        writer.Close();

        //deserialize list from file
        serializer = new XmlSerializer(typeof(List<ProxysNamespace.Person>));
        List<ProxysNamespace.Person> listB;
        using (FileStream file = new FileStream("Test.xml", FileMode.Open))
        {
            //configure proxy reader
            XmlSoapProxyReader reader = new XmlSoapProxyReader(file);
            reader.ProxyNamespace = "http://myappns.com/";      //the namespace of the XmlTypeAttribute 
            reader.ProxyType = typeof(ProxysNamespace.Person); //the type with the XmlTypeAttribute

            //deserialize
            listB = (List<ProxysNamespace.Person>)serializer.Deserialize(reader);
        }

        //display list
        foreach (ProxysNamespace.Person p in listB)
        {
            Console.WriteLine(p.ToString());
        }

        Console.ReadLine();
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime StartDate { get; set; }
    public decimal Money { get; set; }
}

namespace ProxysNamespace
{
    [XmlTypeAttribute(Namespace = "http://myappns.com/")]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Birthday { get; set; }
        public decimal Money { get; set; }

        public override string ToString()
        {
            return string.Format("{0}:{1},{2:d}:{3:c2}", Name, Age, Birthday, Money);
        }
    }
}

public class XmlSoapProxyReader : XmlTextReader
{
    List<object> propNames;
    public XmlSoapProxyReader(Stream input)
        : base(input)
    {
        propNames = new List<object>();
    }

    public string ProxyNamespace { get; set; }

    private Type proxyType;
    public Type ProxyType
    {
        get { return proxyType; }
        set
        {
            proxyType = value;
            PropertyInfo[] properties = proxyType.GetProperties();
            foreach (PropertyInfo p in properties)
            {
                propNames.Add(p.Name);
            }
        }
    }

    public override string NamespaceURI
    {
        get
        {
            object localname = LocalName;
            if (propNames.Contains(localname))
                return ProxyNamespace;
            else
                return string.Empty;
        }
    }
}

这篇关于反序列化XML命名空间没有,但一类期待的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆