예제 #1
0
        public static string Serializer <T>(T t)
        {
            //StringBuilder sb = new StringBuilder();
            using (MemoryStream ms = new MemoryStream())
            {
                using (System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8))
                {
                    XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory();
                    string name = t.GetType().Name;

                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    //Add an empty namespace and empty value
                    ns.Add("", "");

                    XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(typeof(T));

                    xmlSerializer.Serialize(xw, t);

                    // 去除BOM
                    byte[] buffer = ms.ToArray();

                    if (buffer.Length <= 3)
                    {
                        return(Encoding.UTF8.GetString(buffer));
                    }
                    byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
                    if (buffer[0] == bomBuffer[0] && buffer[1] == bomBuffer[1] && buffer[2] == bomBuffer[2])
                    {
                        return(Encoding.UTF8.GetString(buffer, 3, buffer.Length - 3));
                    }
                    return(Encoding.UTF8.GetString(buffer));
                }
            }
        }
예제 #2
0
        //序列化
        public static void ToFile <T>(string path, T obj)
        {
            if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path)))
            {
                File.Create(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path)).Close();
            }

            XmlSerializerFactory factory    = new XmlSerializerFactory();
            XmlSerializer        serializer = factory.CreateSerializer(typeof(T));

            try
            {
                using (FileStream fs = File.Open(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path), FileMode.Create))
                {
                    serializer.Serialize(fs, obj);
                    fs.Flush();
                }
            }
            catch (Exception e)
            {
                StringBuilder error = new StringBuilder();
                error.AppendLine(e.Message);
                error.AppendLine();
                error.AppendFormat("{0}", path);
                error.AppendLine();
                error.AppendFormat("{0}", AppDomain.CurrentDomain.BaseDirectory);
                MessageBox.Show(error.ToString());
            }
        }
        private static XmlSerializer GetSerializerInstance(Type underlingType, XmlAttributeOverrides xmlAttributeOverrides)
        {
            XmlSerializer cachedSerializer = null;

            lock (locker)
            {
                if (m_serializers == null)
                {
                    m_serializers = new Dictionary <Tuple <Type, string>, XmlSerializer>();
                }

                Tuple <Type, string> cacheKey = Tuple.Create(underlingType, string.Empty);

                var xmlRootObject = xmlAttributeOverrides[underlingType].XmlRoot;

                if (xmlRootObject != null)
                {
                    cacheKey = Tuple.Create(underlingType, xmlRootObject.ElementName);
                }

                if (!m_serializers.TryGetValue(cacheKey, out cachedSerializer))
                {
                    cachedSerializer = new XmlSerializerFactory().CreateSerializer(underlingType, xmlAttributeOverrides);
                    m_serializers.Add(cacheKey, cachedSerializer);
                }
            }

            return(cachedSerializer);
        }
예제 #4
0
        internal static T FromXMLFile <T>(string path)
        {
            var x = new XmlDocument();

            x.Load(path);
            if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path)))
            {
                throw new Exception(string.Format("没有找到配置文件:{0}", Path.GetFullPath(path)));
            }
            else
            {
                try
                {
                    XmlSerializerFactory factory    = new XmlSerializerFactory();
                    XmlSerializer        serializer = factory.CreateSerializer(typeof(T));

                    if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path)))
                    {
                        using (FileStream fs = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path)))
                        {
                            if (fs != null && fs.Length > 0)
                            {
                                object cacheData = serializer.Deserialize(fs);
                                return(cacheData == null ? default(T) : (T)cacheData);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                return(default(T));
            }
        }
예제 #5
0
    public async Task Deserialize_HasAllTheValues(string fileName)
    {
        var path = Path.Combine(".", "Data", fileName);

        await using var stream = File.OpenRead(path);

        var factory = new XmlSerializerFactory();

        var serializer = factory.CreateSerializer(typeof(Generated.feed));

        var feed = serializer.Deserialize(stream) as Generated.feed;

        Assert.NotNull(feed);
        AssertNotMalformedString(feed !.title);
        Assert.NotNull(feed.entry);
        Assert.NotEmpty(feed.entry);

        foreach (var entry in feed.entry)
        {
            Assert.NotNull(entry);
            Assert.NotNull(entry.author);
            AssertNotMalformedString(entry.author.name);
            Assert.NotNull(entry.content);
            AssertNotMalformedString(entry.content.Value);
            Assert.NotNull(entry.link);
            AssertNotMalformedString(entry.link.href);
            Assert.Null(entry.link.Value);
            Assert.NotEqual(default, entry.updated);
예제 #6
0
 public static XmlSerializer CreateXmlSerializer <T>(XmlRootAttribute root)
 {
     if (s_Factory == null)
     {
         s_Factory = new XmlSerializerFactory();
     }
     return(s_Factory.CreateSerializer(typeof(T), root));
 }
예제 #7
0
 internal void Save(string filePath)
 {
     using (FileStream fs = new FileStream(filePath, FileMode.Create))
     {
         XmlSerializer xs = new XmlSerializerFactory().CreateSerializer(this.GetType());
         xs.Serialize(fs, this);
     }
 }
예제 #8
0
        public static void Serialization(string path, object target)
        {
            var serializer = new XmlSerializerFactory().CreateSerializer(target.GetType());

            using (Stream stream = new StreamWriter(path).BaseStream)
            {
                serializer.Serialize(stream, target);
            }
        }
예제 #9
0
파일: Client.cs 프로젝트: mykquayce/Helpers
    public Client(HttpClient httpClient, XmlSerializerFactory xmlSerializerFactory)
    {
        Guard.Argument(httpClient).NotNull().Wrap(c => c.BaseAddress !)
        .NotNull().Wrap(u => u.OriginalString)
        .NotNull().NotEmpty().NotWhiteSpace();

        _httpClient           = httpClient;
        _xmlSerializerFactory = Guard.Argument(xmlSerializerFactory).NotNull().Value;
    }
예제 #10
0
        void IXmlSerializable.WriteXml(XmlWriter w)
        {
            if (xmlSerializerCache == null)
            {
                xmlSerializerCache = new XmlSerializerFactory();
            }

            if (this.Count == 0)
            {
                return;
            }

            w.WriteAttributeString("keyType", typeof(Key).AssemblyQualifiedName);
            w.WriteAttributeString("itemType", typeof(Object).AssemblyQualifiedName);

            if (w.LookupPrefix(NamespaceXml.Xsd) == null)
            {
                w.WriteAttributeString("xmlns", "xsd", NamespaceXml.XmlNs, NamespaceXml.Xsd);
            }

            if (w.LookupPrefix(NamespaceXml.Xsi) == null)
            {
                w.WriteAttributeString("xmlns", "xsi", NamespaceXml.XmlNs, NamespaceXml.Xsi);
            }

            XmlSerializer           keySerializer  = xmlSerializerCache.CreateSerializer(typeof(Key));
            XmlSerializer           itemSerializer = xmlSerializerCache.CreateSerializer(typeof(Object));
            XmlSerializerNamespaces ns             = new XmlSerializerNamespaces();

            foreach (Key key in this.Keys)
            {
                int    index = this.positions[key];
                Object value = this[key];

                w.WriteStartElement("key");
                w.WriteAttributeString("index", index.ToString());
                keySerializer.Serialize(w, key, ns);
                w.WriteEndElement();

                w.WriteStartElement("item");
                w.WriteAttributeString("index", index.ToString());
                if (!typeof(Object).IsValueType && value != null && !typeof(Object).Equals(value.GetType()))
                {
                    // items can be inherited objects, so create the XmlSerializer on demand:
                    w.WriteAttributeString("itemType", value.GetType().AssemblyQualifiedName);
                    XmlSerializer inheritedItemSerializer = xmlSerializerCache.CreateSerializer(value.GetType());
                    inheritedItemSerializer.Serialize(w, value, ns);
                }
                else
                {
                    itemSerializer.Serialize(w, value, ns);
                }

                w.WriteEndElement();
            }
        }
예제 #11
0
        private async Task <TDefinitions> GetBpmnDefinition(BPMNOrchestratorInput input)
        {
            var bpmnBytes = await _bpmnProvider.GetBPMN(input.Name);

            using (var stream = new MemoryStream(bpmnBytes))
            {
                var serializer = new XmlSerializerFactory().CreateSerializer(typeof(TDefinitions));
                return(serializer.Deserialize(stream) as TDefinitions);
            }
        }
        private static XmlSerializer GetSerializer()
        {
            var parser = new XmlSerializerFactory().CreateSerializer(typeof(NuGetPackages));

            if (parser == null)
            {
                throw new CommandLineException("Failed to create serialized for parameters xml");
            }

            return(parser);
        }
예제 #13
0
    public WebClientTests()
    {
        var handler = new HttpClientHandler {
            AllowAutoRedirect = false,
        };

        _httpClient = new HttpClient(handler);
        var xmlSerializerFactory = new XmlSerializerFactory();

        _sut = new Concrete.WebClient(_httpClient, xmlSerializerFactory);
    }
예제 #14
0
        public static Stream TransforToXMLFormat(object obj)
        {
            XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory();

            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());

            MemoryStream stream = new MemoryStream();

            xmlSerializer.Serialize(stream, obj);

            return(stream);
        }
예제 #15
0
        public static string SerializeToString(object obj)
        {
            XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
            var serializer = serializerFactory.CreateSerializer(obj.GetType());

            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);

                return(writer.ToString());
            }
        }
예제 #16
0
        ////////////////////////////////////////////////////////

        public static void ReadKeywordMappings()
        {
            property_table = new Hashtable();

            // FIXME: No need for a SerializerFactory here, since we need the serializer
            // only once
            XmlSerializerFactory xsf = new XmlSerializerFactory();
            XmlSerializer        xs  = xsf.CreateSerializer(typeof(QueryMapping), new Type[] { typeof(QueryKeywordMapping) });

            QueryMapping query_mapping = null;

            // <keyword name, can override>
            Dictionary <string, bool> mapping_override = new Dictionary <string, bool> ();

            using (Stream s = File.OpenRead(Path.Combine(PathFinder.ConfigDataDir, "query-mapping.xml"))) {
                try {
                    query_mapping = (QueryMapping)xs.Deserialize(s);
                    foreach (QueryKeywordMapping mapping in query_mapping.Mappings)
                    {
                        PropertyKeywordFu.RegisterMapping(mapping);
                        mapping_override [mapping.Keyword] = true;
                    }
                } catch (XmlException e) {
                    Logger.Log.Error(e, "Unable to parse global query-mapping.xml");
                }
            }

            // Override global mappings by local mappings

            if (!File.Exists(Path.Combine(PathFinder.StorageDir, "query-mapping.xml")))
            {
                return;
            }

            using (Stream s = File.OpenRead(Path.Combine(PathFinder.StorageDir, "query-mapping.xml"))) {
                try {
                    query_mapping = (QueryMapping)xs.Deserialize(s);
                    foreach (QueryKeywordMapping mapping in query_mapping.Mappings)
                    {
                        if (mapping_override.ContainsKey(mapping.Keyword))
                        {
                            property_table.Remove(mapping.Keyword);
                            mapping_override [mapping.Keyword] = false;
                        }

                        PropertyKeywordFu.RegisterMapping(mapping);
                    }
                } catch (XmlException e) {
                    Logger.Log.Error(e, "Unable to parse local query-mapping.xml");
                }
            }
        }
예제 #17
0
    public static T Deserialize <T>(this XElement source) where T : class
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T));

            return((T)serializer.Deserialize(source.CreateReader()));
        }
        catch         //(Exception x)
        {
            return(null);
        }
    }
    public static T LoadFromXmlAsType <T>(this XmlReader xmlReader)
    {
        while (xmlReader.NodeType != XmlNodeType.Element)
        {
            if (!xmlReader.Read())
            {
                throw new XmlException("No root element");
            }
        }
        var serializer = XmlSerializerFactory.Create(typeof(T), xmlReader.LocalName, xmlReader.NamespaceURI);

        return((T)serializer.Deserialize(xmlReader));
    }
    public WebClientFixture()
    {
        _httpMessageHandler = new HttpClientHandler {
            AllowAutoRedirect = false,
        };
        _httpClient = new HttpClient(_httpMessageHandler)
        {
            BaseAddress = new Uri("https://old.reddit.com", UriKind.Absolute),
        };
        var xmlSerializaterFactory = new XmlSerializerFactory();

        WebClient = new Clients.Concrete.WebClient(_httpClient, xmlSerializaterFactory);
    }
예제 #20
0
        public static phonebooks DeserializePhonebookXml(string phonebookUrl)
        {
            var uri = new Uri(phonebookUrl);

            var        factory        = new XmlSerializerFactory();
            var        ser            = factory.CreateSerializer(typeof(phonebooks));
            var        request        = (HttpWebRequest)WebRequest.Create(uri);
            var        response       = (HttpWebResponse)request.GetResponse();
            var        responseStream = response.GetResponseStream();
            phonebooks pbooks         = (phonebooks)ser.Deserialize(responseStream);

            responseStream.Close();
            return(pbooks);
        }
예제 #21
0
        public static void Serialization(string path, object serializationObject)
        {
            if (serializationObject == null)
            {
                return;
            }

            var serializer = new XmlSerializerFactory().CreateSerializer(serializationObject.GetType());

            using (Stream stream = new StreamWriter(path).BaseStream)
            {
                serializer.Serialize(stream, serializationObject);
            }
        }
예제 #22
0
 internal void Load(string filePath)
 {
     using (FileStream fs = new FileStream(filePath, FileMode.Open))
     {
         XmlSerializer xs        = new XmlSerializerFactory().CreateSerializer(this.GetType());
         Estimates     estimates = xs.Deserialize(fs) as Estimates;
         if (estimates != null)
         {
             this.Duration      = estimates.Duration;
             this.RemainingTime = estimates.RemainingTime;
             this.ElapsedTime   = estimates.ElapsedTime;
         }
     }
 }
    public static XElement [] SerializeToXElements <T>(this IEnumerable <KeyValuePair <string, T> > dictionary, XNamespace ns)
    {
        if (dictionary == null)
        {
            return(null);
        }
        ns = ns ?? "";
        var serializer = XmlSerializerFactory.Create(typeof(T), RootLocalName, ns.NamespaceName);
        var array      = dictionary
                         .Select(p => new { p.Key, Value = p.Value.SerializeToXElement(serializer, true) })
                         // Fix name and remove redundant xmlns= attributes.  XmlWriter will add them back if needed.
                         .Select(p => new XElement(ns + p.Key, p.Value.Attributes().Where(a => !a.IsNamespaceDeclaration), p.Value.Elements()))
                         .ToArray();

        return(array);
    }
예제 #24
0
    public static T DeserializePolymorphic <T>(this XElement value, XName name)
    {
        if (value == null)
        {
            return(default(T));
        }
        var typeName = (string)value.Attribute(TypeAttributeName);

        if (typeName == null)
        {
            throw new InvalidOperationException(string.Format("Missing AssemblyQualifiedName for \"{0}\"", value.ToString()));
        }
        var type = Type.GetType(typeName, true);     // Throw on error

        return((T)value.Deserialize(type, XmlSerializerFactory.Create(type, name)));
    }
예제 #25
0
 public void Save()
 {
     if (!Directory.GetParent(SettingsFilePath).Exists)
     {
         Directory.GetParent(SettingsFilePath).Create();
     }
     using (FileStream fs = new FileStream(SettingsFilePath, FileMode.Create))
     {
         XmlSerializer xs = new XmlSerializerFactory().CreateSerializer(this.GetType());
         if (xs != null)
         {
             xs.Serialize(fs, this);
         }
     }
     IsDirty = false;
 }
예제 #26
0
    public ClientFixture()
    {
        var baseAddress = new Uri("https://old.reddit.com", UriKind.Absolute);

        _httpClientHandler = new HttpClientHandler {
            AllowAutoRedirect = false,
        };
        _httpClient = new HttpClient(_httpClientHandler)
        {
            BaseAddress = baseAddress,
        };

        var xmlSerializerFactory = new XmlSerializerFactory();

        Client = new Helpers.Reddit.Concrete.Client(_httpClient, xmlSerializerFactory);
    }
예제 #27
0
 private void SaveFile(string filePath)
 {
     if (!Directory.GetParent(filePath).Exists)
     {
         Directory.GetParent(filePath).Create();
     }
     else if (File.Exists(filePath) && File.GetAttributes(filePath).HasFlag(FileAttributes.ReadOnly))
     {
         File.SetAttributes(filePath, FileAttributes.Normal);
     }
     using (FileStream fs = new FileStream(filePath, FileMode.Create))
     {
         XmlSerializer xs = new XmlSerializerFactory().CreateSerializer(this.GetType());
         xs.Serialize(fs, this);
     }
 }
예제 #28
0
        public static T Deserialization <T>(string path)
        {
            if (File.Exists(path))
            {
                var serializer = new XmlSerializerFactory().CreateSerializer(typeof(T));

                using (Stream stream = new StreamReader(path).BaseStream)
                {
                    object deserializedObject = serializer.Deserialize(stream);

                    if (deserializedObject is T)
                    {
                        return((T)deserializedObject);
                    }
                }
            }
            return(default);
    public static IEnumerable <T> DeserializeElements <T>(this XmlReader reader, string localName, string namespaceUri)
    {
        var serializer = XmlSerializerFactory.Create(typeof(T), localName, namespaceUri);

        while (!reader.EOF)
        {
            if (!(reader.NodeType == XmlNodeType.Element && reader.LocalName == localName && reader.NamespaceURI == namespaceUri))
            {
                reader.ReadToFollowing(localName, namespaceUri);
            }

            if (!reader.EOF)
            {
                yield return((T)serializer.Deserialize(reader));
                // Note that the serializer will advance the reader past the end of the node
            }
        }
    }
예제 #30
0
        public static T Load <T>(string path)
        {
            if (!File.Exists(path))
            {
                throw new CommandLineException("Failed to find file at {0}", path);
            }

            using (var file = File.OpenRead(path))
            {
                var parser = new XmlSerializerFactory().CreateSerializer(typeof(T));
                if (parser == null)
                {
                    throw new CommandLineException("Failed to create serialized for " + typeof(T).FullName);
                }

                return((T)parser.Deserialize(file));
            }
        }
예제 #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Create factory early
        XmlSerializerFactory factory = new XmlSerializerFactory();

        XmlReaderSettings settings = new XmlReaderSettings();

        NameTable nt = new NameTable();
        object book = nt.Add("book");
        object price = nt.Add("price");
        object author = nt.Add("author");
        settings.NameTable = nt;

        string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd");

        settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile));
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags =

        XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler +=
                new ValidationEventHandler(settings_ValidationEventHandler);

        settings.IgnoreWhitespace = true;
        settings.IgnoreComments = true;

        string booksFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml");
        using (XmlReader reader = XmlReader.Create(booksFile, settings))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element &&
                   author.Equals(reader.LocalName))
                {
                    //Then use the factory to create and cache serializers
                    XmlSerializer xs = factory.CreateSerializer(typeof(Author));
                    Author a = (Author)xs.Deserialize(reader.ReadSubtree());
                    Response.Write(String.Format("Author: {1}, {0}<BR/>",
                        a.FirstName, a.LastName));
                }
            }
        }
    }
예제 #32
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Double price = 49.99;
        DateTime publicationdate = new DateTime(2005, 1, 1);
        String isbn = "1-057-610-0";
        Author a = new Author();
        a.FirstName = "Scott";
        a.LastName = "Hanselman";

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.NewLineOnAttributes = true;

        Response.ContentType = "text/xml";

        XmlSerializerFactory factory = new XmlSerializerFactory();

        using (XmlWriter writer =
                XmlWriter.Create(Response.OutputStream, settings))
        {
            //Note the artificial, but useful, indenting
            writer.WriteStartDocument();
            writer.WriteStartElement("bookstore");
            writer.WriteStartElement("book");
            writer.WriteStartAttribute("publicationdate");
            writer.WriteValue(publicationdate);
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("ISBN");
            writer.WriteValue(isbn);
            writer.WriteEndAttribute();
            writer.WriteElementString("title", "ASP.NET 2.0");
            writer.WriteStartElement("price");
            writer.WriteValue(price);
            writer.WriteEndElement(); //price
            XmlSerializer xs = factory.CreateSerializer(typeof(Author));
            xs.Serialize(writer, a);
            writer.WriteEndElement(); //book
            writer.WriteEndElement(); //bookstore
            writer.WriteEndDocument();
        }
    }