following is the part of my xml serializing object.
private decimal tOAMOUNTField;
public decimal TOAMOUNT
{
get
{
return this.tOAMOUNTField;
}
set
{
this.tOAMOUNTField = value;
}
}
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyClassObject));
var entity = new Myobject();
entity .TOAMOUNT = 2.22M;
using (StringWriter sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
// sww.WriteLine(#"<?xml version=""1.0"" encoding=""UTF-8""?>");
xsSubmit.Serialize(writer , entity);
output = sww.ToString();
}
}
above mention "ToAmount" Property is not serializing in XML
Kindly point out the mistake because all other properties are serializing
You are initializing a XmlSerializer object with type MyClassObject.
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyClassObject));
But are serializing a 'Myobject()' object.
Try changing it in:
XmlSerializer xsSubmit = new XmlSerializer(typeof(Myobject));
Related
Seen lots of people with this same issue and no answers anywhere, so answering it myself here;
When serializing an XML class that should have a prefix attached to it, the prefix is missing.
[XmlRoot(ElementName = "Preadvice", Namespace = "http://www.wibble.com/PreadviceRequest")]
public class Preadvice
{
}
var XMLNameSpaces = new XmlSerializerNamespaces();
XMLNameSpaces.Add("isd", "http://www.wibble.com/PreadviceRequest");
And this is my serializing method;
public static string SerializeStandardObject<T>(T obj, XmlSerializerNamespaces ns, XmlAttributeOverrides xao, XmlRootAttribute xra)
{
XmlSerializer serializer = new XmlSerializer(typeof(T), (xao == null ? new XmlAttributeOverrides() : xao), new Type[] { obj.GetType() }, (xra == null ? new XmlRootAttribute(obj.GetType().Name) : xra), "");
using (StringWriter sw = new StringWriter())
{
using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
{
serializer.Serialize(writer, obj, (ns == null ? new XmlSerializerNamespaces() : ns));
}
return sw.ToString();
}
}
This produces;
<?xml version="1.0" encoding="utf-16"?>
<Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</Preadvice>
Which is missing the prefix, it should look like this..
<?xml version="1.0" encoding="utf-16"?>
<isd:Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</isd:Preadvice>
If your serializer includes an xmlrootattribute when it is created, it doesn't apply namespaces you have specified manually, and therefore misses the "isd" tag off the first element. The easiest fix is to remove the xmlrootattribute;
public static string SerializeStandardObject<T>(T obj, XmlSerializerNamespaces ns)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringWriter sw = new StringWriter())
{
using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
{
serializer.Serialize(writer, obj, (ns == null ? new XmlSerializerNamespaces() : ns));
}
return sw.ToString();
}
}
I'm not experienced in XML-serialization. I need to serialize System.Collections.Generic.List to XML document. I have the following classes:
public class Person
{
public string Name;
public string Phone;
public Int32 Score;
}
[Serializable()]
public class PersonOperation:Person
{
public String City;
public String OperationType;
public DateTime OperationDate;
public Decimal Amount;
public Decimal AmountEUR;
public void RoubleToEuro(CurrencyCode p_CurrencyCode, Decimal p_CurrencyRate)
{
if (p_CurrencyCode == CurrencyCode.Euro)
{
this.AmountEUR = Decimal.Round(Amount / p_CurrencyRate, 2);
}
}
}
I have a collection of PersonOperation instances that I must serialize to XML.
private List<PersonOperation> _depositorsOperationsList = new List<PersonOperation>();
For XML serialization I try to use the following method:
public XmlDocument GetEntityXml<T>()
{
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attr = new XmlAttributes();
attr.XmlRoot = new XmlRootAttribute("Operation");
overrides.Add(typeof(List<T>), attr);
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), overrides);
ser.Serialize(writer, _depositorsOperationsList);
}
return xmlDoc;
}
I'm in need of the following XML-format after serialization:
<?xml version="1.0" encoding="Windows-1251" ?>
<Operation>
<PersonOperation>
<Name>John Smith</Name>
<Phone>79161234586</Phone>
<City>Glasgow</City>
<Date>2014-02-03</Date>
<OperationType>Join</OperationType>
<Amount>9000.00</Amount>
<AmountEUR>144.06</AmountEUR>
</PersonOperation>
<PersonOperation>
<Name>Bill Satly</Name>
<Phone>79163214569</Phone>
<City>London</City>
<Date>2014-07-10</Date>
<OperationType>Join</OperationType>
<Amount>9000.00</Amount>
<AmountEUR>144.06</AmountEUR>
</PersonOperation>
. . . . . . . . . . .
<Operation>
But instead of this format I have the following one-line horror:
<Operation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><PersonOperation><Name>John Smith</Name><Phone>79161234586</Phone><Score>270</Score><City>Glasgow</City><OperationType>Join</OperationType><OperationDate>2014-02-03</OperationDate><Amount>9000.0000</Amount><AmountEUR>144.06</AmountEUR></PersonOperation><PersonOperation><Name>Bill Satly</Name><Phone>79163214569</Phone><Score>270</Score><City>London</City><OperationType>Join</OperationType><OperationDate>2014-07-10</OperationDate><Amount>9000.0000</Amount><AmountEUR>144.06</AmountEUR></PersonOperation></Operation>
How can I repair my GetEntityXml method for correct XML-format?
The XmlWriter has a Settings property of type XmlWriterSettings.
Try using that to specify the formatting to be used.
using (XmlWriter writer = nav.AppendChild())
{
writer.Settings.Indent = true;
XmlSerializer ser = new XmlSerializer(typeof(List<T>), overrides);
ser.Serialize(writer, _depositorsOperationsList);
}
More information here:
https://msdn.microsoft.com/en-us/library/kbef2xz3(VS.80).aspx
If you open your file with special XML editor or just with web navigator like chrome or internet explorer it will look like you want.
Just pasting snippet from my code that works fine..
Public Function ToXmlString() As String
Dim builder = New StringBuilder()
Dim xmlSerializer = New XmlSerializer(GetType(List(Of T)), New XmlRootAttribute(_rootNodeName))
Using writer = XmlWriter.Create(builder, New XmlWriterSettings() With {.OmitXmlDeclaration = True})
xmlSerializer.Serialize(writer, _source)
End Using
Return builder.ToString()
End Function
---- Converted C# Code ----
public string ToXmlString()
{
var builder = new StringBuilder();
var xmlSerializer = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(_rootNodeName));
using (writer = XmlWriter.Create(builder, new XmlWriterSettings { OmitXmlDeclaration = true })) {
xmlSerializer.Serialize(writer, _source);
}
return builder.ToString();
}
where _rootNodeName is name of your root node of xml and _source is sourceList
And then to create XMLDoc from string --
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlString);
I need to get clear xml without any namespace and type declarations. Here is the serialized xml:
<placeBetRequest p1:type="PlaceBetRequestTeamed" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">
...
</placeBetRequest>
Need to someway configure XmlSerializer to set it don't add any attributes but only mine (if I set them with [XmlAttribte]
the clean xml need to looks like this:
<placeBetRequest>
...
</placeBetRequest>
Here is my serialization method:
public static string XmlConvert<T>(T obj, params Type[] wellKnownTypes) where T : class
{
var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var settings = new XmlWriterSettings {Indent = true, OmitXmlDeclaration = true};
XmlSerializer serializer = wellKnownTypes == null
? new XmlSerializer(typeof(T))
: new XmlSerializer(typeof(T), wellKnownTypes);
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, obj, emptyNamepsaces);
return stream.ToString();
}
}
Please help. Thanks.
I've been using regex
string input =
"<p1:placeBetRequest p1:type=\"PlaceBetRequestTeamed\" xmlns:p1=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"</p1:placeBetRequest>";
string pattern = #"(?'prefix'\</?)(?'ns'[^:]*:)";
string output = Regex.Replace(input, pattern, "${prefix}");
I'm having problem deserializing previously serialized XML.
My class is generated from .xsd by xsd.exe utility. I have no influence on the structure of .xsd as it was issued by government, and used to standardize communication...
The problem is, when I create an object, set some properties on it, then serialize it using XmlSerializer, and then deserialize it back, I do not get the same "contents" as I started with. Some of the elements from XML deserialize in "Any" property instead of properties from which these elements were serialized in a first place.
Perhaps a clumsy explanation, but I've created a sample project that reproduces my issue.
Sample project can be found here.
Edit:
Ok, here is some sample code. Unfortunately I can't paste everything here, because file generated by xsd.exe is over 4000 lines long. But everything required is in linked file.
My test console app:
static void Main(string[] args)
{
Pismeno pismeno = new Pismeno();
#region Build sample content
pismeno.Sadrzaj = new SadrzajTip();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<SomeXml xmlns=\"http://some.namespace.com/\">Some content goes here</SomeXml>");
pismeno.Sadrzaj.Item = xmlDoc.DocumentElement;
pismeno.Prilog = new PismenoPrilog[1];
pismeno.Prilog[0] = new PismenoPrilog();
pismeno.Prilog[0].VrijemeNastanka = DateTime.Now.ToString("s");
XmlDocument xmlTitle = new XmlDocument();
xmlTitle.LoadXml("<Title xmlns=\"http://some.namespace.com/\">Test title 1</Title>");
pismeno.Prilog[0].Any = new XmlElement[1];
pismeno.Prilog[0].Any[0] = xmlTitle.DocumentElement;
pismeno.Prilog[0].Sadrzaj = new SadrzajTip();
EAdresaTip eat = new EAdresaTip();
eat.URL = "http://www.example.com/testfile.doc";
pismeno.Prilog[0].Sadrzaj.Item = eat;
#endregion
// Serialize object, and then deserialize it again
string pismenoSer = Serialize(pismeno);
Pismeno pismeno2 = Deserialize<Pismeno>(pismenoSer);
// Objects to compare. "source" has source.Sadrzaj and source.Prilog properties set
// "shouldBeTheSameAsSource" has shouldBeTheSameAsSource.Any property set
Pismeno source = pismeno;
Pismeno shouldBeTheSameAsSource = pismeno2;
}
public static string Serialize(object o)
{
string ret = null;
using (var stream = new MemoryStream())
{
XmlWriter xw = new XmlTextWriter(stream, Encoding.UTF8) { Formatting = Formatting.Indented };
new XmlSerializer(o.GetType()).Serialize(xw, o);
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
ret = (new StreamReader(stream, Encoding.UTF8)).ReadToEnd();
}
return ret;
}
public static T Deserialize<T>(string xml)
{
return (T)new XmlSerializer(typeof(T)).Deserialize(XmlReader.Create(new StringReader(xml)));
}
I have a library that contains a .NET type. The library has its own configuration (annotations etc) for serializing the type to XML, and I do not have the source code.
No matter what I do, I could not manage to add the prefix I want to add to the root element of the output XML. Using XmlSerializerNamespaces made no difference. Here is a snippet that shows my code at the moment:
var comp = row[0] as LibraryType;
var ser = new XmlSerializer(comp.GetType());
var strWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(strWriter);
ser.Serialize(xmlWriter, comp);
string serXml = strWriter.ToString();
Is there a way in configure XMLSerializer to create an xlm output for root such as
<lt:LibraryType ....
instead of the current
<LibraryType .....
I'm getting ?
Lets say that your library type looks like
public class Foo
{
public int i { get; set; }
}
public class Bar
{
public Foo Foo { get; set; }
}
then serialization should look like
var comp = new Bar {Foo = new Foo()};
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof (Bar), new XmlAttributes {XmlRoot = new XmlRootAttribute {Namespace = "http://tempuri.org"}});
// in case you want to remove prefix from members
var emptyNsAttribute = new XmlAttributes();
emptyNsAttribute.XmlElements.Add(new XmlElementAttribute { Namespace = "" });
overrides.Add(typeof(Bar), "Foo", emptyNsAttribute);
// if you actual library type contains more members, then you have to list all of them
var ser = new XmlSerializer(comp.GetType(), overrides);
var strWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(strWriter);
var ns = new XmlSerializerNamespaces();
ns.Add("lt", "http://tempuri.org");
ser.Serialize(xmlWriter, comp, ns);
string serXml = strWriter.ToString();
and the output will be
<?xml version="1.0" encoding="utf-16"?><lt:Bar xmlns:lt="http://tempuri.org"><Foo><i>0</i></Foo></lt:Bar>