XmlSerializer : Remove xmlns:xsd but keep xmlns:xsi - c#

I'm using this method to generate an XML :
using (MemoryStream msRes = new MemoryStream())
using (StreamWriter objStreamWriter = new StreamWriter(msRes))
using (XmlWriter xw = XmlWriter.Create(objStreamWriter, new XmlWriterSettings() { Indent = true, IndentChars = String.Empty }))
{
XmlSerializer serializer = new XmlSerializer(doc.GetType());
serializer.Serialize(xw, doc);
return msRes.ToArray();
}
The result is that I have this sort of line <Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.02">.
I'd like to remove the attribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" but keep xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.02".
How can I do that ?
Thanks for your help !

You could try the below code to remove the xmlns entries:
var ns = new XmlSerializerNamespaces(); ns.Add("", "");

Related

Adding an xsd file value to an XmlAttribute

How I am creating an xml string of proper xml with the code below..
string myInputXmlString = #"<ApplicationData>
<something>else</something>
</ApplicationData>";
var doc = new XmlDocument();
doc.LoadXml(myInputXmlString);
XmlAttribute newAttr = doc.CreateAttribute(
"xsi",
"noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance");
doc.DocumentElement.Attributes.Append(newAttr);
var ms = new MemoryStream();
XmlWriterSettings ws = new XmlWriterSettings
{
OmitXmlDeclaration = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = UTF8Encoding.UTF8
};
var tx = XmlWriter.Create(ms, ws);
doc.Save(tx);
tx.Flush();
var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(xmlString);
How do I add the xsd information to this so the xml looks like this (with "FullModeDataset.xsd" includded?
<ApplicationData
xsi:noNamespaceSchemaLocation="FullModeDataset.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
Instead of this which the current code is outputing
<ApplicationData
xsi:noNamespaceSchemaLocation=""
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
Does this work by chance?
doc.DocumentElement.SetAttribute("noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance",
"FullModeDataset.xsd");

Serialize a .net object and omit the doctype?

I've written some .net code to serialize an object using the XMLSerializer class.
public static string serialize(object o)
{
Type type = o.GetType();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
System.IO.StringWriter writer = new System.IO.StringWriter();
serializer.Serialize(writer, o);
return writer.ToString();
}
The output looks like this:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>a</string>
<string>b</string>
<string>c</string>
</ArrayOfString>
That's great, but what I would really like is to get just the root node without the XML doctype declaration at the beginning.
The reason I want to do this is because I would like to use the root element of the XML serialized object as part of another XML document.
XmlWriterSettings has a property to omit the XML declaration (OmitXmlDeclaration):
public static string Serialize(object obj)
{
var builder = new StringBuilder();
var xmlSerializer = new XmlSerializer(obj.GetType());
using (XmlWriter writer = XmlWriter.Create(builder,
new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
xmlSerializer.Serialize(writer, obj);
}
return builder.ToString();
}

How to set XmlWriter.XmlWriterSettings when created from XPathNavigator.AppendChild()?

I need to set the OmitXmlDeclaration property of the XmlWriterSettings for a XmlWriter to false to not have XML declarations created. The issue is that I have created the XmlWriter from a call of a XPathNavigator.AppendChild() method. Code below:
public String GetEntityXml<T>(List<T> entities)
{
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
ser.Serialize(writer, entities);
}
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlTextWriter);
string resultString = stringWriter.ToString();
stringWriter.Close();
xmlTextWriter.Close();
return resultString;
}
Any idea how to serialize the List and not have XML declarations?
I’m not getting the XML declaration when I execute your code. Serializing a List<int> gives me:
<Int32_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<int>5</int>
<int>7</int>
<int>2</int>
</Int32_LIST>
Note that the “XML declaration” that OmitXmlDeclaration refers to is typically something similar to:
<?xml version="1.0" encoding="UTF-8" ?>
If you’re instead referring to the xmlns parts, then those are called “XML namespace declarations”, and may be eliminated by initializing an XmlSerializerNamespaces instance with a default empty namespace, and passing it to your Serialize method:
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
ser.Serialize(writer, entities, namespaces);
The below is a shortened implementation which achieves the same result as your code:
public String GetEntityXml<T>(List<T> entities)
{
var sb = new StringBuilder();
var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
ser.Serialize(writer, entities, namespaces);
}
return sb.ToString();
}
Try this approach (switched to var for readability):
public String GetEntityXml<T>(List<T> entities)
{
var xmlDoc = new XmlDocument();
var nav = xmlDoc.CreateNavigator();
using (var sw = new StringWriter())
{
//Create an XmlWriter that will omit xml declarations
var s = new XmlWriterSettings{ OmitXmlDeclaration = true };
using (var xmlWriter = XmlWriter.Create(sw, s))
{
//Use the following to serialize without namespaces
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var ser = new XmlSerializer(typeof(List<T>),
new XmlRootAttribute(typeof(T).Name + "_LIST"));
ser.Serialize(xmlWriter, entities, ns);
}
//Pass xml string to nav.AppendChild()
nav.AppendChild(sw.ToString());
}
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter);
}
return stringWriter.ToString();
}
}
Rather than using nav.AppendChild() to create the XmlWriter, you can create the XmlWriter separately and then just use nav.AppendChild(string) to write the XML into xmlDoc. When you create the XmlWriter yourself, you can omit the XML declaration. Also, when you serialize, you'll probably want to omit the xmlns:xsi and xmlns:xsd namespaces using the XmlSerializerNamespaces class.

How can I make the xmlserializer only serialize plain xml?

I need to get plain xml, without the <?xml version="1.0" encoding="utf-16"?> at the beginning and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" in first element from XmlSerializer. How can I do it?
To put this all together - this works perfectly for me:
// To Clean XML
public string SerializeToString<T>(T value)
{
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(value.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, emptyNamespaces);
return stream.ToString();
}
}
Use the XmlSerializer.Serialize method overload where you can specify custom namespaces and pass there this.
var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(xmlWriter, objectToSerialze, emptyNs);
passing null or empty array won't do the trick
You can use XmlWriterSettings and set the property OmitXmlDeclaration to true as described in the msdn. Then use the XmlSerializer.Serialize(xmlWriter, objectToSerialize) as described here.
This will write the XML to a file instead of a string. Object ticket is the object that I am serializing.
Namespaces used:
using System.Xml;
using System.Xml.Serialization;
Code:
XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlSerializer serializer = new XmlSerializer(typeof(ticket));
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (XmlWriter xmlWriter = XmlWriter.Create(fullPathFileName, settings))
{
serializer.Serialize(xmlWriter, ticket, emptyNamespaces);
}

C# XNode add a NameSpace

I have a xNode made by JSON.
C# code:
Class class = new Class();
class.ComboBoxChecked = Class.ComboBoxChecked;
class.RadioButtonChecked = Class.RadioButtonChecked;
string test = JsonConvert.SerializeObject(class);
XNode node = JsonConvert.DeserializeXNode(test, "Root");
XML:
<Root>
<RadioButtonChecked>1</RadioButtonChecked>
<ComboBoxChecked>5</ComboBoxChecked>
</Root>
My goal is to add a Namespace to it.
How can i achieve this?
You can add namespaces at root level this way:
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("example", "http://www.w3.org");
using (var ms = new MemoryStream())
{
using (TextWriter writer = new StreamWriter(ms))
{
var xmlSerializer = new XmlSerializer(typeof(MyClass));
xmlSerializer.Serialize(writer, myClassInstance, ns);
XNode node = XElement.Parse(Encoding.ASCII.GetString(ms.ToArray()));
}
}
If you need namespaces in it's children, you can edit your class using the IXmlSerializable interface, here's an Example

Categories

Resources