Destroy XML without namespaces, but in a class that expects namespaces

Duplicate:
Omit all xml namespaces when serializing an object? Not the same. I want another way: Deserialize!


I have a C # class as shown below:

[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
    { ...

I use this class to serialize / deserialize XML files as requested by the user. But I have a problem: a namespace definition has been added to the new version of this software. The XML is the same, just adding a namespace definition.

For example, the latest version ...

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

and the new version ...

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

I need to load XML files with and without these namespaces. I have many nested classes, and each of them has its own namespace definition.

XML, .

XmlTextReader NamespaceURI, , . , .NET XML.

+3
4

-. , , XmlSerializer - . , , XmlTypeAttribute - , Visual Studio.

, , . . XmlTextReader, , . , , -.

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

XML , XmlRoot , :

[XmlRoot(ElementName="plugins", Namespace="")]

Xml

<plugins><...

, :

[XmlRoot(ElementName="plugins", Namespace="")]
public class Plugins
{
   //...
}

, , :

using (FileStream stream = File.Open(filePath, FileMode.Open))
{
   XmlReader reader = new XmlTextReader(stream);                
   XmlSerializer serializer = new XmlSerializer(typeof(Plugins));
   var plugins = (Plugins)serializer.Deserialize(reader);
}

-stan

+5

, , .

You may need to write “good” text back to the [memory / string / etc] stream to invoke the XmlSerializer deserializer.

+1
source

You need to implement IXmlSerializable to improve your custom serialization.

-1
source

Source: https://habr.com/ru/post/1733519/


All Articles