Add() публичный Метод

public Add ( string prefix, string ns ) : void
prefix string
ns string
Результат void
Пример #1
0
        public string Cancelar()
        {
            try
            {
                XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
                nameSpaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                nameSpaces.Add("tipos", "http://*****:*****@"D:\Ret_CANC_LOTE_2805131157.xml";

                RetornoCancelamentoNFSe objretorno = SerializeClassToXml.DeserializeClasse<RetornoCancelamentoNFSe>(sPathRetConsultaCanc);

                string sMessageRetorno = TrataRetornoCancelamento(objretorno);
                return sMessageRetorno;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #2
0
        public byte[] getRequestContent( string doctype, string root, Type type, object obj)
        {
            XmlSerializer serializer = null;
            if (root == null)
            {
                //... root element will be the object type name
                serializer = new XmlSerializer(type);
            }
            else
            {
                //... root element set explicitely
                var xattribs = new XmlAttributes();
                var xroot = new XmlRootAttribute(root);
                xattribs.XmlRoot = xroot;
                var xoverrides = new XmlAttributeOverrides();
                xoverrides.Add(type, xattribs);
                serializer = new XmlSerializer(type, xoverrides);
            }
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = false;
            settings.OmitXmlDeclaration = false;
            settings.Encoding = new UTF8Encoding(false/*no BOM*/, true/*throw if input illegal*/);

            XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
            xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlNameSpace.Add("noNamespaceSchemaLocation", m_schemadir + "/" + doctype + "." + m_schemaext);

            StringWriter sw = new StringWriter();
            XmlWriter xw = XmlWriter.Create( sw, settings);
            xw.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");

            serializer.Serialize(xw, obj, xmlNameSpace);

            return settings.Encoding.GetBytes( sw.ToString());
        }
Пример #3
0
 public AccessPointInfoBase()
 {
     this.typeField = "tdc:Door";
     xmlns          = new XmlSerializerNamespaces();
     xmlns.Add("tdc1", "http://www.onvif.org/ver10/doorcontrol/wsdl");
     xmlns.Add("not", "http://www.onvif.org/v3/notDoorControl/wsdl");
 }
Пример #4
0
        public XmlDocument ToXML()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                // xmlns:georss="http://www.georss.org/georss"
                // xmlns:gml="http://www.opengis.net/gml"
                //xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
                //xmlns:kml="http://www.opengis.net/kml/2.2"
                //xmlns:dc="http://purl.org/dc/elements/1.1/"
                var ns = new XmlSerializerNamespaces();
                ns.Add("georss", "http://www.georss.org/georss");
                ns.Add("gml", "http://www.opengis.net/gml");
                ns.Add("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#");
                ns.Add("kml", "http://www.opengis.net/kml/2.2");
                ns.Add("dc", "http://purl.org/dc/elements/1.1/");

                XmlSerializer s = new XmlSerializer(this.GetType());
                Console.WriteLine("Testing for type: {0}", this.GetType());
                s.Serialize(XmlWriter.Create(stream), this, ns);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                //object o = s.Deserialize(XmlReader.Create(stream));
                //Console.WriteLine("  Deserialized type: {0}", o.GetType());
                XmlDocument xml = new XmlDocument();
                xml.Load(stream);
                Console.Write(xml.InnerXml);
                return xml;
            }

            //var serializer = new XmlSerializer(this.GetType());
            //serializer.Serialize(new StreamWriter("test.xml"), this);
        }
Пример #5
0
        /// <summary>
        /// Parses the export file at the specified disk path.
        /// </summary>
        /// <param name="diskPathToExportFile">The disk path to the export file.</param>
        public Feed Parse(string diskPathToExportFile)
        {
            diskPathToExportFile.CheckNullOrEmpty("diskPathToExportFile");

            Log.InfoFormat("blogger2jekyll.Blogger.ExportXmlParses conversion started at {0}.", DateTime.Now);
            Log.InfoFormat("Using Blogger import file at {0}", diskPathToExportFile);

            XmlDocument sourceDocument = new XmlDocument();
            sourceDocument.Load(diskPathToExportFile);

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);
            ns.Add("app", "http://purl.org/atom/app#");

            XmlSerializer serializer = new XmlSerializer(typeof(Feed));
            Feed feed = (Feed)serializer.Deserialize(new StringReader(sourceDocument.OuterXml));

            ProcessComments(feed);
            ProcessPages(feed);
            ProcessSettings(feed);

            Log.InfoFormat("blogger2jekyll.Blogger.ExportXmlParses conversion completed at {0}.", DateTime.Now);
            Log.InfoFormat("The blog {0} was converted.", feed.Title);
            Log.InfoFormat("{0} posts were found in the export file.", feed.Posts.Count);

            return feed;
        }
		public bool WriteObject(XPathResult result, XPathNavigator node, object value)
		{
			var rootOverride = new XmlRootAttribute(node.LocalName)
			{
				Namespace = node.NamespaceURI
			};

			var xml = new StringBuilder();
			var settings = new XmlWriterSettings
			{
				OmitXmlDeclaration = true,
				Indent = false
			};
			var namespaces = new XmlSerializerNamespaces();
			namespaces.Add(string.Empty, string.Empty);
			if (string.IsNullOrEmpty(node.NamespaceURI) == false)
			{
				var prefix = result.Context.AddNamespace(node.NamespaceURI);
				namespaces.Add(prefix, node.NamespaceURI);
			}

			var serializer = new XmlSerializer(result.Type, rootOverride);

			using (var writer = XmlWriter.Create(xml, settings))
			{
				serializer.Serialize(writer, value, namespaces);
				writer.Flush();
			}

			node.ReplaceSelf(xml.ToString());

			return true;
		}
        public void DeserializeCapabilities()
        {
            System.IO.FileStream atom         = new System.IO.FileStream("../../Terradue.Portal/Schemas/examples/geohazards-capabilities.xml", System.IO.FileMode.Open);
            XmlSerializer        serializer   = new XmlSerializer(typeof(WPSCapabilitiesType));
            WPSCapabilitiesType  capabilities = (WPSCapabilitiesType)serializer.Deserialize(atom);

            Assert.AreEqual("Geohazard Tep WPS", capabilities.ServiceIdentification.Title[0].Value);
            Assert.AreEqual("WPS", capabilities.ServiceIdentification.ServiceType.Value);
            Assert.AreEqual(4, capabilities.ServiceIdentification.Keywords[0].Keyword.Count);
            Assert.AreEqual("Geohazards Tep", capabilities.ServiceProvider.ProviderName);
            Assert.AreEqual(3, capabilities.OperationsMetadata.Operation.Count);
            Assert.AreEqual(28, capabilities.ProcessOfferings.Process.Count);
            Assert.AreEqual("2ceb1e69-6ab2-4dab-9f7e-4a594924267c", capabilities.ProcessOfferings.Process[0].Identifier.Value);
            Assert.AreEqual("ASAR PF", capabilities.ProcessOfferings.Process[0].Title.Value);
            Assert.AreEqual("The ENVISAT ASAR PF is the ESA operational Level-1 processor developed by MDA. This processor, integrated on the ESA's Grid Processing On Demand , perform on-demand production of L1 products.", capabilities.ProcessOfferings.Process[0].Abstract.Value);

            var stream = new MemoryStream();

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            ns.Add("wps", "http://www.opengis.net/wps/1.0.0");
            ns.Add("ows", "http://www.opengis.net/ows/1.1");
            ns.Add("xlink", "http://www.w3.org/1999/xlink");
            serializer.Serialize(stream, capabilities, ns);
            stream.Seek(0, SeekOrigin.Begin);
            string capabilitiesText;

            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                capabilitiesText = reader.ReadToEnd();
            }
            Assert.IsNotNull(capabilitiesText);
        }
        public void DeserializeExecute()
        {
            System.IO.FileStream atom       = new System.IO.FileStream("../../Terradue.Portal/Schemas/examples/execute.xml", System.IO.FileMode.Open);
            XmlSerializer        serializer = new XmlSerializer(typeof(Execute));
            Execute execute = (Execute)serializer.Deserialize(atom);

            Assert.AreEqual("b4d3a590-c29c-46db-9b55-7e82cf74ab2e", execute.Identifier.Value);
            Assert.AreEqual(14, execute.DataInputs.Count);
            Assert.True(execute.DataInputs[1].Data.Item is BoundingBoxType);
            Assert.AreEqual("-54.58 35.532", ((BoundingBoxType)execute.DataInputs[1].Data.Item).LowerCorner);
            Assert.AreEqual("-16.875 59.356", ((BoundingBoxType)execute.DataInputs[1].Data.Item).UpperCorner);

            var stream = new MemoryStream();

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            ns.Add("wps", "http://www.opengis.net/wps/1.0.0");
            ns.Add("ows", "http://www.opengis.net/ows/1.1");
            ns.Add("xlink", "http://www.w3.org/1999/xlink");
            serializer.Serialize(stream, execute, ns);
            stream.Seek(0, SeekOrigin.Begin);
            string executeText;

            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                executeText = reader.ReadToEnd();
            }
            Assert.IsNotNull(executeText);
        }
Пример #9
0
        public void Write(Stream outputStream, object artifact)
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new XmlSerializer(artifact.GetType(), "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                ns.Add("ds", "http://schemas.allscripts.com/cds/evaluation");
                ns.Add("am", "http://schemas.allscripts.com/mom");
                serializer.Serialize(stream, artifact, ns);

                // This seems like a bug with the serializer to me, but the outer-most instance of
                // Composite expression within the artifact is serialized with the prefix ds, instead
                // of am, even though the CompositeAssertion class has the XmlNamespaceAttribute with
                // allscripts.com/mom as given above. So we serialize the output to a temporary stream,
                // read it into a string, replace the offending instance with the correct value, and
                // then write the output stream with that string.
                stream.Position = 0;
                using (var sr = new StreamReader(stream))
                {
                    var result = sr.ReadToEnd();

                    using (var sw = new StreamWriter(outputStream))
                    {
                        sw.Write(result.Replace("ds:CompositeAssertion", "am:CompositeAssertion"));
                    }
                }
            }
        }
Пример #10
0
        public static void SaveDelta(Delta delta, string file)
        {
            var ns = new XmlSerializerNamespaces();
            ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");

            var serializer = new XmlSerializer(typeof(Delta));
            
            var list = new List<ImportObject>();
            foreach (var obj in delta.Objects.Where(x => x.NeedsInclude()))
            {
                var newObj = new ImportObject();
                newObj.SourceObjectIdentifier = obj.SourceObjectIdentifier;
                newObj.TargetObjectIdentifier = obj.TargetObjectIdentifier;
                newObj.ObjectType = obj.ObjectType;
                newObj.State = obj.State;
                newObj.Changes = obj.Changes != null ? obj.Changes.Where(x => x.IsIncluded).ToArray() : null;
                newObj.AnchorPairs = obj.AnchorPairs;
                list.Add(newObj);
            }

            var newDelta = new Delta();
            newDelta.Objects = list.ToArray();

			var settings = new XmlWriterSettings();
			settings.OmitXmlDeclaration = false;
			settings.Indent = true;
            using (var w = XmlWriter.Create(file, settings))
                serializer.Serialize(w, newDelta, ns);
        }
        public void DeserializeExecuteResponse()
        {
            System.IO.FileStream atom       = new System.IO.FileStream("../../Terradue.Portal/Schemas/examples/executeresponse.xml", System.IO.FileMode.Open);
            XmlSerializer        serializer = new XmlSerializer(typeof(ExecuteResponse));
            ExecuteResponse      execute    = (ExecuteResponse)serializer.Deserialize(atom);

            Assert.AreEqual("com.terradue.wps_oozie.process.OozieAbstractAlgorithm", execute.Process.Identifier.Value);
            Assert.AreEqual("ADORE DORIS interferometric processor", execute.Process.Title.Value);
            Assert.True(execute.Status.Item is ProcessAcceptedType);

            var stream = new MemoryStream();

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            ns.Add("wps", "http://www.opengis.net/wps/1.0.0");
            ns.Add("ows", "http://www.opengis.net/ows/1.1");
            ns.Add("xlink", "http://www.w3.org/1999/xlink");
            serializer.Serialize(stream, execute, ns);
            stream.Seek(0, SeekOrigin.Begin);
            string executeText;

            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                executeText = reader.ReadToEnd();
            }
            Assert.IsNotNull(executeText);
        }
Пример #12
0
        public Step()
        {
            ScreenAnnotations = new List<ScreenAnnotation>();

            Xmlns = new XmlSerializerNamespaces();
            Xmlns.Add("ns3", ScenarioDocuXMLFileUtil.ScenarioNameSpace);
            Xmlns.Add("xs", ScenarioDocuXMLFileUtil.XmlSchema);
        }
Пример #13
0
        public UseCase()
        {
            Xmlns = new XmlSerializerNamespaces();
            Xmlns.Add("ns3", ScenarioDocuXMLFileUtil.ScenarioNameSpace);
            Xmlns.Add("xs", ScenarioDocuXMLFileUtil.XmlSchema);

            Details = new Details();
        }
Пример #14
0
 /// <summary>
 /// helper
 /// </summary>
 /// <returns></returns>
 public static System.Xml.Serialization.XmlSerializerNamespaces GetNamespaces()
 {
     System.Xml.Serialization.XmlSerializerNamespaces ns;
     ns = new System.Xml.Serialization.XmlSerializerNamespaces();
     ns.Add("", "http://www.w3.org/2001/XMLSchema");
     ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
     return(ns);
 }
 public SpreadsheetXmlSerializer()
 {
     _xmlSerializer = new XmlSerializer(typeof (Workbook), "urn:schemas-microsoft-com:office:spreadsheet");
     _xmlNamespaces = new XmlSerializerNamespaces();
     _xmlNamespaces.Add("ss", "urn:schemas-microsoft-com:office:spreadsheet");
     _xmlNamespaces.Add("x", "urn:schemas-microsoft-com:office:excel");
     _xmlNamespaces.Add("o", "urn:schemas-microsoft-com:office:office");
     _xmlNamespaces.Add("c", "urn:schemas-microsoft-com:office:component:spreadsheet");
     _xmlNamespaces.Add("html", "http://www.w3.org/TR/REC-html40");
 }
Пример #16
0
        public static Rss ReadRSS(Stream source)
        {
            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add("atom", "http://www.w3.org/2005/Atom");
            xsn.Add("dc", "http://purl.org/dc/elements/1.1/");
            xsn.Add("content", "http://purl.org/rss/1.0/modules/content/");

            XmlSerializer ser = new XmlSerializer(typeof(Rss));
            return (Rss)ser.Deserialize(source);
        }
Пример #17
0
        public static void WriteRss(Structure.RssFeed value, Stream destination)
        {
            var xsn = new XmlSerializerNamespaces();
            xsn.Add("atom", "http://www.w3.org/2005/Atom");
            xsn.Add("dc", "http://purl.org/dc/elements/1.1/");
            xsn.Add("content", "http://purl.org/rss/1.0/modules/content/");

            var ser = new XmlSerializer(value.GetType());
            ser.Serialize(destination, value, xsn);
        }
Пример #18
0
        public static Structure.RssFeed ReadRss(Stream source)
        {
            var xsn = new XmlSerializerNamespaces();
            xsn.Add("atom", "http://www.w3.org/2005/Atom");
            xsn.Add("dc", "http://purl.org/dc/elements/1.1/");
            xsn.Add("content", "http://purl.org/rss/1.0/modules/content/");

            var ser = new XmlSerializer(typeof(Structure.RssFeed));
            return (Structure.RssFeed)ser.Deserialize(source);
        }
Пример #19
0
        public Scenario()
        {
            Xmlns = new XmlSerializerNamespaces();
            Xmlns.Add("ns3", ScenarioDocuXMLFileUtil.ScenarioNameSpace);
            Xmlns.Add("xs", ScenarioDocuXMLFileUtil.XmlSchema);

            Name = string.Empty;
            Description = string.Empty;
            Status = string.Empty;
            Details = new Details();
        }
Пример #20
0
        public static void Serialize(Manifest manifest, StreamWriter writer)
        {
            var xs = new XmlSerializer(typeof(Manifest));

            var xsn = new XmlSerializerNamespaces();
            xsn.Add(SCORM.Adlcp, SCORM.AdlcpNamespaceV1P3);
            xsn.Add(SCORM.Imsss, SCORM.ImsssNamespace);
            xsn.Add(SCORM.Adlseq, SCORM.AdlseqNamespace);
            xsn.Add(SCORM.Adlnav, SCORM.AdlnavNamespace);
            xsn.Add(SCORM.Imsss, SCORM.ImsssNamespace);

            xs.Serialize(writer, manifest, xsn);
        }
Пример #21
0
        public void Serialize(string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(UrlSet), "");
            StreamWriter writer = new StreamWriter(path);

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9");
            ns.Add("image", "http://www.google.com/schemas/sitemap-image/1.1");
            ns.Add("video", "http://www.google.com/schemas/sitemap-video/1.1");

            serializer.Serialize(writer, this, ns);

            writer.Close();
            writer.Dispose();
        }
Пример #22
0
        public string ToXml()
        {
            string ret = "";

            Type serializableObjectType = this.GetType();

            using (System.IO.StringWriter output = new System.IO.StringWriter(new System.Text.StringBuilder())) {
                System.Xml.Serialization.XmlSerializer           s   = new System.Xml.Serialization.XmlSerializer(serializableObjectType);
                System.Xml.Serialization.XmlSerializerNamespaces xsn = new System.Xml.Serialization.XmlSerializerNamespaces();
                xsn.Add("", "");


                // get a list of the xml type attributes so that we can clean up the xml. In other words. remove extra namespace text.
                object[] attributes = serializableObjectType.GetCustomAttributes(typeof(System.Xml.Serialization.XmlTypeAttribute), false);
                if (attributes != null)
                {
                    System.Xml.Serialization.XmlTypeAttribute xta;
                    for (int i = 0; i < attributes.Length; i++)
                    {
                        xta = (System.Xml.Serialization.XmlTypeAttribute)attributes[i];
                        //xsn.Add("ns" + 1, xta.Namespace);
                    }
                }

                s.Serialize(output, this, xsn);
                ret = output.ToString().Replace("utf-16", "utf-8").Trim();
            }

            return(ret);
        }
Пример #23
0
        /*
         *  // use reflection to get all derived types
         *      var knownTypes = Assembly.GetExecutingAssembly().GetTypes().Where( t => typeof(Car).IsAssignableFrom(t) || typeof(Wheel).IsAssignableFrom(t) || typeof(Door).IsAssignableFrom(t)).ToArray();
         *
         *      // prepare to serialize a car object
         *      XmlSerializer serializer = new XmlSerializer(typeof(Car), knownTypes);
         */

        public static string Serialize(object objectToSerialize, System.Text.Encoding encoding, bool formatXml, bool removeNamespaces)
        {
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());

            string xml = "";

            using (MemoryStream memoryStream = new MemoryStream())
            {
                ModifiedXmlTextWriter xmlTextWriter = new ModifiedXmlTextWriter(memoryStream, encoding);
                if (removeNamespaces)
                {
                    System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();
                    namespaces.Add("", "");
                    xs.Serialize(xmlTextWriter, objectToSerialize, namespaces);
                }
                else
                {
                    xs.Serialize(xmlTextWriter, objectToSerialize);
                }
                byte[] bytes = memoryStream.ToArray();
                xml = encoding.GetString(bytes);
            }

            if (formatXml)
            {
                return(Utility.FormatXml(xml));
            }
            else
            {
                return(xml);
            }
        }
        public override int Run(string[] args)
        {
            string schemaFileName = args[0];
            string outschemaFileName = args[1];

            XmlTextReader xr = new XmlTextReader(schemaFileName);
            SchemaInfo schemaInfo = SchemaManager.ReadAndValidateSchema(xr, Path.GetDirectoryName(schemaFileName));
            schemaInfo.Includes.Clear();
            schemaInfo.Classes.Sort(CompareNames);
            schemaInfo.Relations.Sort(CompareNames);

            XmlSerializer ser = new XmlSerializer(typeof(SchemaInfo));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", SchemaInfo.XmlNamespace);

            using (FileStream fs = File.Create(outschemaFileName))
            {
                try
                {
                    ser.Serialize(fs, schemaInfo, ns);
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
            }

            return 0;
        }
Пример #25
0
        public static byte[] getRequestContent(string doctype, string root, Type type, object obj)
        {
            var xattribs = new XmlAttributes();
            var xroot = new XmlRootAttribute(root);
            xattribs.XmlRoot = xroot;
            var xoverrides = new XmlAttributeOverrides();
            //... have to use XmlAttributeOverrides because .NET insists on the object name as root element name otherwise ([XmlRoot(..)] has no effect)
            xoverrides.Add(type, xattribs);

            XmlSerializer serializer = new XmlSerializer(type, xoverrides);
            StringWriter sw = new StringWriter();
            XmlWriterSettings wsettings = new XmlWriterSettings();
            wsettings.OmitXmlDeclaration = false;
            wsettings.Encoding = new UTF8Encoding();
            XmlWriter xw = XmlWriter.Create(sw, wsettings);
            xw.WriteProcessingInstruction("xml", "version='1.0' standalone='no'");
            //... have to write header by hand (OmitXmlDeclaration=false has no effect)
            xw.WriteDocType(root, null, doctype + ".sfrm", null);

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            //... trick to avoid printing of xmlns:xsi xmlns:xsd attributes of the root element

            serializer.Serialize(xw, obj, ns);
            return sw.ToArray();
        }
Пример #26
0
        //private readonly Utilities sUtilities = Singleton<Utilities>.Instance;
        /// <summary>
        /// Serializes the current instance and returns the result as a <see cref="string"/>
        /// <para>Should be used with XML serialization only.</para>
        /// </summary>
        /// <returns>The serialized instance.</returns>
        public string Serialize()
        {
            //if(!sPlatform.IsLinux)
            //	Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

            string data;

            try
            {
                using(var ms = new MemoryStream())
                {
                    var serializer = new XmlSerializer(GetType());
                    var nss = new XmlSerializerNamespaces();
                    nss.Add(string.Empty, string.Empty);
                    serializer.Serialize(ms, this, nss);

                    using(var reader = new StreamReader(ms))
                    {
                        data = reader.ReadToEnd();
                    }
                }
            }
            catch(InvalidOperationException x)
            {
                throw new WolframException(sLConsole.GetString("Error during serialization"), x);
            }

            if(string.IsNullOrEmpty(data))
                throw new WolframException(string.Format(sLConsole.GetString("Error while serializing instance! Type: {0}"), GetType().FullName));

            return data;
        }
Пример #27
0
        public void ExportDefinition(Project project)
        {
            TextWriter resultsWriter = new StringWriter();
            XmlTextWriter xslResultsWriter = new XmlTextWriter(resultsWriter);
            MemoryStream outStrm = new MemoryStream();

            XmlSerializer xs = new XmlSerializer(typeof(Project));
            TextWriter stringWriter = new StringWriter();
            XmlTextWriter xtr = new XmlTextWriter(stringWriter);

            string xmlnamespace = _Settings.XmlNameSpace;
            XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
            xns.Add("tt", xmlnamespace);
            try
            {
                //xs.Serialize(xtr, model, xns);
                xs.Serialize(outStrm, project, xns);
            }
            catch (Exception ee)
            {
                string m = ee.Message;
            }
            outStrm.Position = 0;

            FileStream fs = new FileStream(Settings.FileName, FileMode.OpenOrCreate, FileAccess.Write);
            outStrm.WriteTo(fs);
            fs.Flush();
            fs.Close();
            //string str = stringWriter.ToString();
            outStrm.Position = 0;
        }
        public static string Serialize <T>(this T value)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            try
            {
                var xmlserializer = new XmlSerializer(typeof(T));
                var ns            = new System.Xml.Serialization.XmlSerializerNamespaces();
                ns.Add("", "");
                var stringWriter = new StringWriter();
                using (var writer = XmlWriter.Create(stringWriter, new XmlWriterSettings {
                    OmitXmlDeclaration = true,
                }))
                {
                    xmlserializer.Serialize(writer, value, ns);
                    return(stringWriter.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred", ex);
            }
        }
    /// <summary>
    /// This method converts any object into xml format.
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
        public static string SerializeData(object data)
        {
            //StringBuilder sbData = new StringBuilder();
            //StringWriter swWriter;
            //XmlSerializer employeeSerializer = new XmlSerializer(typeof(object));

            //swWriter = new StringWriter(sbData);
            //employeeSerializer.Serialize(swWriter, data);
            //return sbData.ToString();

            if (data == null)
            {
                return string.Empty;
            }
            try
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(String.Empty, String.Empty);
                var xmlserializer = new XmlSerializer(data.GetType(),String.Empty);
                var stringWriter = new StringWriter();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                using (var writer = XmlWriter.Create(stringWriter,settings))
                {
                    xmlserializer.Serialize(writer, data,ns);
                    return stringWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred", ex);
            }
        }
Пример #30
0
        public async Task<HttpResponseMessage> Post() {
            TextMessage recievedMessage;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(TextMessage));
            
            Stream stream = await Request.Content.ReadAsStreamAsync();
            using (var reader = new StreamReader(stream)) {
                
                recievedMessage = (TextMessage)xmlSerializer.Deserialize(reader);
            }
            
            TextMessage sendingMessage = new TextMessage() { 
                ToUserName = recievedMessage.FromUserName,
                FromUserName = recievedMessage.ToUserName,
                CreateTime = ConvertToUnixTimestamp(DateTime.Now).ToString(),
                Content = recievedMessage.Content
            };

            Trace.TraceInformation(Request.Headers.Accept.ToString());

            string messageStr = string.Empty;
            using (StringWriter textWriter = new StringWriter()) {
                var xns = new XmlSerializerNamespaces();
                xns.Add(string.Empty, string.Empty);
                xmlSerializer.Serialize(textWriter, sendingMessage, xns);
                messageStr = textWriter.ToString();
            }

            return new HttpResponseMessage() {
                Content = new StringContent(
                    messageStr,
                    Encoding.UTF8,
                    "text/html"
                )
            };
        }
Пример #31
0
        public XmlElement SerializeGovTalkMessageGovTalkDetails(hmrcclasses.GovTalkMessageGovTalkDetails gtDetails)
        {
            // copy of IRenvelope serializer

            using (MemoryStream memStream = new MemoryStream())
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(String.Empty, "http://www.govtalk.gov.uk/CM/envelope");

                var knownTypes = new Type[] { typeof(hmrcclasses.GovTalkMessageGovTalkDetails), typeof(hmrcclasses.GovTalkMessageGovTalkDetailsKey) };

                XmlSerializer serializer =
                    new XmlSerializer(typeof(hmrcclasses.GovTalkMessageGovTalkDetails), knownTypes);

                XmlTextWriter tw = new XmlTextWriter(memStream, UTF8Encoding.UTF8);

                XmlDocument doc = new XmlDocument();
                tw.Formatting = Formatting.Indented;
                tw.IndentChar = ' ';
                serializer.Serialize(tw, gtDetails, ns);
                memStream.Seek(0, SeekOrigin.Begin);
                doc.Load(memStream);
                XmlElement returnVal = doc.DocumentElement;

                return returnVal;
            }
        }
Пример #32
0
 static XmlSerializerAdapter()
 {
     settings = new XmlWriterSettings();
     settings.OmitXmlDeclaration = true;
     ns = new XmlSerializerNamespaces();
     ns.Add("", "");
 }
Пример #33
0
        // Similar code exist in O2.DotNetWrappers.DotNet.Serialize
        public static bool createSerializedXmlFileFromObject(Object oObjectToProcess, String sTargetFile, Type[] extraTypes)
        {
            FileStream fileStream = null;
            try
            {
                var xnsXmlSerializerNamespaces = new XmlSerializerNamespaces();
                xnsXmlSerializerNamespaces.Add("", "");
                var xsXmlSerializer = (extraTypes != null)
                                          ? new XmlSerializer(oObjectToProcess.GetType(), extraTypes)
                                          : new XmlSerializer(oObjectToProcess.GetType());

                fileStream = new FileStream(sTargetFile, FileMode.Create);

                xsXmlSerializer.Serialize(fileStream, oObjectToProcess, xnsXmlSerializerNamespaces);
                //fileStream.Close();

                return true;
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "In createSerializedXmlStringFromObject");
                return false;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

        }
Пример #34
0
        static XmlConfigService()
        {
            _xmlSerializer = new XmlSerializer(typeof(JobSchedulingData));

            _xmlSerializerNamespaces = new XmlSerializerNamespaces();
            _xmlSerializerNamespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        }
Пример #35
0
        public static String createSerializedXmlStringFromObject(Object oObjectToProcess , Type[] extraTypes)
        {
            if (oObjectToProcess == null)
                DI.log.error("in createSerializedXmlStringFromObject: oObjectToProcess == null");
            else
            {
                try
                {
                    /*// handle cases file names are bigger than 220
                    if (sTargetFile.Length > 220)
                    {
                        sTargetFile = sTargetFile.Substring(0, 200) + ".xml";
                        DI.log.error("sTargetFile.Length was > 200, so renamig it to: {0}", sTargetFile);
                    }*/
                    var xnsXmlSerializerNamespaces = new XmlSerializerNamespaces();
                    xnsXmlSerializerNamespaces.Add("", "");
                    var xsXmlSerializer = (extraTypes != null)
                                              ? new XmlSerializer(oObjectToProcess.GetType(), extraTypes)
                                              : new XmlSerializer(oObjectToProcess.GetType());
                    var memoryStream = new MemoryStream();
                    xsXmlSerializer.Serialize(memoryStream, oObjectToProcess, xnsXmlSerializerNamespaces);

                    return Encoding.ASCII.GetString(memoryStream.ToArray());
                }
                catch (Exception ex)
                {
                    DI.log.ex(ex,"In createSerializedXmlStringFromObject");
                }
            }
            return "";
        }
Пример #36
0
 /// <summary>
 /// Сериализация Базы знаний в xml.
 /// </summary>
 /// <param name="frames"></param>
 /// <returns></returns>
 public bool SaveXml(GroopFrame frames)
 {
     bool result = false;
     using (StreamWriter writer =
         new StreamWriter("frame.xml"))
     {
         try
         {
             XmlSerializerNamespaces ns =
                 new XmlSerializerNamespaces();
             ns.Add("", "");
             XmlSerializer serializer =
                 new XmlSerializer(frames.GetType());
             serializer.Serialize(writer, frames, ns);
             result = true;
         }
         catch (Exception e)
         {
             // Логирование
         }
         finally
         {
             writer.Close();
         }
     }
     return result;
 }
Пример #37
0
 public static void Serialize(Stream stream, object value) {
     var ns = new XmlSerializerNamespaces();
     ns.Add("", "");
     var serializer = new XmlSerializer(value.GetType(), "");
     using (var xml = XmlWriter.Create(stream, XmlWriterSettings))
         serializer.Serialize(xml, value, ns);
 }
Пример #38
0
        public void TestMethod1()
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(TestSection));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            var mySection = new TestSection();
            mySection.myDecimal = 2.15M;
            mySection.myInt = 215;
            mySection.myString = "215";
            using (StringWriter sww = new StringWriter())
            using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings() { OmitXmlDeclaration = true }))
            {
                xsSubmit.Serialize(writer, mySection, ns);
                var xml = sww.ToString();
            }

            // Save Xml            
            string configutaionFilePath = Environment.CurrentDirectory;
            var Xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                        <configuration>
                              <configSections>
                              </configSections>
                        </configuration>
                        ";

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(Xml);
            xdoc.Save(configutaionFilePath + @"\config.xml");
        }
Пример #39
0
        /// <summary>
        /// 转换为xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="NotNs">不包含命名空间</param>
        /// <returns></returns>
        private static string ObjToXml <T>(T entity, bool NotNs)
        {
            string        result     = string.Empty;
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                XmlWriterSettings setting = new XmlWriterSettings();
                setting.Encoding = new UTF8Encoding(false);
                setting.Indent   = true;
                XmlWriter writer = XmlWriter.Create(stream, setting);
                System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
                if (NotNs)
                {
                    ns.Add("", "");//不输出xmlns
                }
                serializer.Serialize(writer, entity, ns);
                stream.Position = 0;
                byte[] buf = new byte[stream.Length];
                stream.Read(buf, 0, buf.Length);
                //result = Convert.ToBase64String(buf);
                result = System.Text.Encoding.UTF8.GetString(buf);
            }
            return(result);
        }
Пример #40
0
        public void Serialize(Type type, object data, Stream outStream)
        {
            xml.XmlSerializer           serializer = new xml.XmlSerializer(type);
            xml.XmlSerializerNamespaces ns         = new xml.XmlSerializerNamespaces();
            ns.Add("xlink", "http://www.w3.org/1999/xlink");

            serializer.Serialize(outStream, data, ns);
        }
Пример #41
0
 public ClipStorage()
 {
     if (s_ser == null)
     {
         s_ser = new XmlSerializer(typeof(Clips));
         s_xsn = new XmlSerializerNamespaces();
         s_xsn.Add("", "");
     }
 }
Пример #42
0
 public string ObjectToXml <T>(T objectToSerialise)
 {
     System.IO.StringWriter Output = new System.IO.StringWriter(new StringBuilder());
     System.Xml.Serialization.XmlSerializer           xs = new System.Xml.Serialization.XmlSerializer(objectToSerialise.GetType());
     System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
     ns.Add("fac", "http://www.facturante.com.API");
     xs.Serialize(Output, objectToSerialise, ns);
     return(Output.ToString());
 }
Пример #43
0
        /// <summary>   Saves to document format. </summary>
        ///
        /// <remarks>   Asim Naeem, 7/20/2017. </remarks>
        ///
        /// <param name="serializableObject">       Serializable object to be saved to file. </param>
        /// <param name="extraTypes">               Extra data types to enable serialization of custom
        ///                                         types within the object. </param>
        /// <param name="path">                     Path of the file to save the object to. </param>
        /// <param name="isolatedStorageFolder">    Pathname of the isolated storage folder. </param>


        private static void SaveToDocumentFormat(T serializableObject, System.Type[] extraTypes, string path, IsolatedStorageFile isolatedStorageFolder)
        {
            using (TextWriter textWriter = CreateTextWriter(isolatedStorageFolder, path))
            {
                XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
                var           xmlns         = new System.Xml.Serialization.XmlSerializerNamespaces();
                xmlns.Add(string.Empty, string.Empty);
                xmlSerializer.Serialize(textWriter, serializableObject, xmlns);
            }
        }
        public void DeserializeDescribeProcess()
        {
            System.IO.FileStream atom       = new System.IO.FileStream("../../Terradue.Portal/Schemas/examples/describeprocess.xml", System.IO.FileMode.Open);
            XmlSerializer        serializer = new XmlSerializer(typeof(ProcessDescriptions));
            ProcessDescriptions  describe   = (ProcessDescriptions)serializer.Deserialize(atom);

            Assert.AreEqual("com.terradue.wps_oozie.process.OozieAbstractAlgorithm", describe.ProcessDescription[0].Identifier.Value);
            Assert.AreEqual("SRTM Digital Elevation Model", describe.ProcessDescription[0].Title.Value);
            Assert.AreEqual(2, describe.ProcessDescription[0].DataInputs.Count);
            Assert.AreEqual("Level0_ref", describe.ProcessDescription[0].DataInputs[0].Identifier.Value);
            Assert.AreEqual("string", describe.ProcessDescription[0].DataInputs[0].LiteralData.DataType.Value);
            Assert.AreEqual("https://data.terradue.com/gs/catalogue/tepqw/gtfeature/search?format=json&uid=ASA_IM__0PNPAM20120407_082248_000001263113_00251_52851_2317.N1", describe.ProcessDescription[0].DataInputs[0].LiteralData.DefaultValue);
            Assert.AreEqual("format", describe.ProcessDescription[0].DataInputs[1].Identifier.Value);
            Assert.AreEqual("string", describe.ProcessDescription[0].DataInputs[1].LiteralData.DataType.Value);
            Assert.AreEqual("gamma", describe.ProcessDescription[0].DataInputs[1].LiteralData.DefaultValue);
            Assert.AreEqual(2, describe.ProcessDescription[0].ProcessOutputs.Count);
            Assert.AreEqual("result_distribution", describe.ProcessDescription[0].ProcessOutputs[0].Identifier.Value);
            Assert.True(describe.ProcessDescription[0].ProcessOutputs[0].Item is SupportedComplexDataType);
            Assert.AreEqual("result_osd", describe.ProcessDescription[0].ProcessOutputs[1].Identifier.Value);

            var stream = new MemoryStream();

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            ns.Add("wps", "http://www.opengis.net/wps/1.0.0");
            ns.Add("ows", "http://www.opengis.net/ows/1.1");
            ns.Add("xlink", "http://www.w3.org/1999/xlink");
            serializer.Serialize(stream, describe, ns);
            stream.Seek(0, SeekOrigin.Begin);
            string executeText;

            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                executeText = reader.ReadToEnd();
            }
            Assert.IsNotNull(executeText);
        }
Пример #45
0
        public static void Object2XmlFile(object obj, string sFileName)
        {
            var x  = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            var ns = new System.Xml.Serialization.XmlSerializerNamespaces();

            ns.Add("", "");
            using (var fs = new System.IO.FileStream(sFileName, System.IO.FileMode.Create))
            {
                var settings = new System.Xml.XmlWriterSettings();
                settings.Indent             = true;
                settings.OmitXmlDeclaration = true;
                settings.Encoding           = System.Text.Encoding.UTF8;
                var writer = System.Xml.XmlWriter.Create(fs, settings);
                x.Serialize(writer, obj, ns);
            }
        }
Пример #46
0
        public string ToXml()
        {
            //メモリストリームに一旦書き出す
            using (var stream = new System.IO.MemoryStream())
                using (var writer = new System.IO.StreamWriter(stream, System.Text.Encoding.UTF8))
                {
                    System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
                    ns.Add(String.Empty, String.Empty);

                    //シリアライズ
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CommentPostData));
                    serializer.Serialize(writer, this, ns);
                    writer.Flush();
                    return(Encoding.UTF8.GetString(stream.ToArray()));
                }
        }
Пример #47
0
        /// <summary>
        /// Serializer T to xml
        /// </summary>
        /// <typeparam name="T">the type</typeparam>
        /// <param name="t">the T entity</param>
        /// <returns>return a xml string</returns>
        public static string SerializerToStream <T>(T t)
        {
            System.Xml.Serialization.XmlSerializer           xs = new System.Xml.Serialization.XmlSerializer(t.GetType());
            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            // Add two namespaces with prefixes.
            ns.Add(string.Empty, string.Empty);
            MemoryStream      stream  = new MemoryStream();
            XmlWriterSettings setting = new XmlWriterSettings();

            setting.Encoding = new UTF8Encoding(false);
            setting.Indent   = true;
            using (XmlWriter writer = XmlWriter.Create(stream, setting))
            {
                xs.Serialize(writer, t, ns);
            }

            return(Encoding.UTF8.GetString(stream.ToArray()));
        }
Пример #48
0
        public void Serialize<T>(Stream stream, T data)
        {
            var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
            using (var writer = XmlWriter.Create(stream, settings))
            {
                var ns = new Xml.XmlSerializerNamespaces();

                if (typeof(T).Namespace == HermesNameSpace)
                {
                    ns.Add("", Facade.XmlNamespaces.Default);
                }

                var serializer = new Xml.XmlSerializer(typeof(T));
                serializer.Serialize(writer, data, ns);

                writer.Close();
            }
        }
Пример #49
0
        public static string Object2Xml(object obj)
        {
            string sXml = "";
            var    x    = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            var    ns   = new System.Xml.Serialization.XmlSerializerNamespaces();

            ns.Add("", "");
            using (var ms = new System.IO.MemoryStream())
            {
                var settings = new System.Xml.XmlWriterSettings();
                settings.Indent             = false;
                settings.OmitXmlDeclaration = true;
                settings.Encoding           = System.Text.Encoding.UTF8;
                var writer = System.Xml.XmlWriter.Create(ms, settings);
                x.Serialize(writer, obj, ns);
                sXml = System.Text.Encoding.UTF8.GetString(ms.GetBuffer());
            }
            return(sXml);
        }
Пример #50
0
        /// <summary>
        /// Serializer Xml To File
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="fileFullPath"></param>
        public static void SerializerXmlToFile <T>(T t, string fileFullPath)
        {
            System.Xml.Serialization.XmlSerializer serializer
                = new System.Xml.Serialization.XmlSerializer(t.GetType());

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            // Add two namespaces with prefixes.
            ns.Add(string.Empty, string.Empty);
            //ns.Add("ExportDate", DateTime.Now.ToString() );

            Stream        fs     = new FileStream(fileFullPath, FileMode.OpenOrCreate);
            XmlTextWriter writer = new XmlTextWriter(fs, Encoding.GetEncoding("utf-8"));

            writer.Formatting  = Formatting.Indented;
            writer.Indentation = 4;

            // Serialize using the XmlTextWriter.
            serializer.Serialize(writer, t, ns);
            writer.Close();
        }
Пример #51
0
        private static string SystemXmlWriter <T>(T value, System.Xml.XmlWriterSettings settings)
        {
            if (value == null)
            {
                return(String.Empty);
            }

            var buffer = new System.Text.StringBuilder();
            var writer = System.Xml.XmlWriter.Create(buffer, settings);

            var namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();

            namespaces.Add(String.Empty, String.Empty);            // tricks the serializer into not emitting default xmlns attributes

            // serialize feed
            var serializer = new System.Xml.Serialization.XmlSerializer(value.GetType());

            serializer.Serialize(writer, value, namespaces);

            return(buffer.ToString());
        }
Пример #52
0
    private static string ToXML <T>(T obj, bool includetype, bool indent = false)
    {
        if (includetype)
        {
            XElement xml = XMLConverter.ToXml(obj, null, includetype);

            if (indent)
            {
                return(xml.ToString());
            }
            else
            {
                return(xml.ToString(SaveOptions.DisableFormatting));
            }
        }
        else
        {
            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            XmlSerializer xs       = new XmlSerializer(typeof(T));
            StringBuilder sbuilder = new StringBuilder();
            var           xmlws    = new System.Xml.XmlWriterSettings()
            {
                OmitXmlDeclaration = true, Indent = indent
            };
            ns.Add(string.Empty, string.Empty);
            using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
            {
                xs.Serialize(writer, obj, ns);
            }
            string result = sbuilder.ToString();
            ns       = null;
            xs       = null;
            sbuilder = null;
            xmlws    = null;
            return(result);
        }
    }
Пример #53
0
 static ChoNullNSXmlSerializer()
 {
     _xmlnsEmpty.Add("", "");
 }
Пример #54
0
 static XmlSerializer()
 {
     defaultNamespaces = new XmlSerializerNamespaces();
     defaultNamespaces.Add("xsi", XmlSchema.InstanceNamespace);
     defaultNamespaces.Add("xsd", XmlSchema.Namespace);
 }
Пример #55
0
        public static bool Submit(string url, CapitalRequest cr, TradeLink.API.DebugDelegate deb)
        {
            d = deb;
            if (cr.usingresults && !ResultsSubmittable(cr.SubmittedResults))
            {
                debug("To submit capital connection request, results must be profitable over at least two symbol days.");
                return(false);
            }
            HttpWebRequest hr = WebRequest.Create(url) as HttpWebRequest;

            //hr.Credentials = new System.Net.NetworkCredential(user, password);
            //hr.PreAuthenticate = true;
            //hr.Headers.Add(
            hr.Method = "POST";
            //hr.ContentType = "application/xml";

            XmlWriterSettings writerSettings = new XmlWriterSettings();

            writerSettings.OmitXmlDeclaration = true;
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CapitalRequest));

            XmlWriter xmlWriter = XmlTextWriterFormattedNoDeclaration.Create(stringWriter, writerSettings);

            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            ns.Add("", "");

            serializer.Serialize(xmlWriter, cr, ns);
            string xml = stringWriter.ToString();

            System.Xml.Linq.XDocument xd = System.Xml.Linq.XDocument.Parse(xml);
            StringBuilder             sb = new StringBuilder();
            // get parameter list
            int i = 0;

            foreach (System.Xml.Linq.XElement xe in xd.Descendants())
            {
                if (xe.HasElements)
                {
                    continue;
                }
                if (i++ > 0)
                {
                    sb.Append("&");
                }
                if (xe.Name.LocalName.ToLower() == "result")
                {
                    sb.Append(xe.Name.LocalName + "=" + System.Web.HttpUtility.HtmlEncode(xe.Value));
                }
                else
                {
                    sb.Append(xe.Name.LocalName + "=" + xe.Value);
                }
            }
            string data = sb.ToString();

            // encode
            byte[] bytes = UTF8Encoding.UTF8.GetBytes(data);
            hr.ContentLength = bytes.Length;
            // prepare id
            int id = 0;

            try
            {
                // write it
                System.IO.Stream post = hr.GetRequestStream();
                post.Write(bytes, 0, bytes.Length);
                // get response
                System.IO.StreamReader response = new System.IO.StreamReader(hr.GetResponse().GetResponseStream());
                // get string version
                string key = response.ReadToEnd();
                // display it
                debug("added request: " + key);
                return(true);
            }
            catch (Exception ex)
            {
                debug("error adding: " + Util.Serialize <CapitalRequest>(cr) + " " + ex.Message + ex.StackTrace);
                return(false);
            }
        }