When using the default settings with the XmlSerializer it will output the XML as a formated value.
IE: something along these lines.
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Stock>
<ProductCode>12345</ProductCode>
<ProductPrice>10.32</ProductPrice>
</Stock>
<Stock>
<ProductCode>45632</ProductCode>
<ProductPrice>5.43</ProductPrice>
</Stock>
</ArrayOfStock>
How does one prevent any type of formatting on the output? So what I am looking to achieve is this.
<?xml version="1.0" encoding="utf-8"?><ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Stock><ProductCode>123456</ProductCode><ProductPrice>10.57</ProductPrice></Stock><Stock><ProductCode>789123</ProductCode><ProductPrice>133.22</ProductPrice></Stock></ArrayOfStock>
EDIT: The full code of my method is
public static String Serialize(Stock stock)
{
XmlSerializer serializer = new XmlSerializer(typeof(Stock));
using (StringWriter stringWriter = new StringWriter())
{
serializer.Serialize(stringWriter, stock);
return stringWriter.ToString();
}
}
Not very intuitive, but the Indent property on the XmlWriterSettings controls the whole formatting:
var serializer = new XmlSerializer(typeof(MyClass));
using (var writer = new StreamWriter("file.path"))
using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = false }))
{
serializer.Serialize(xmlWriter, myObject);
}
There are a few more options on XmlWriterSettings that you might want to explore.
It is simple to parse the resulting XML and remove and newlines and tabs...
using 'Indent = false', will still put elements on newlines no?
..
XmlSerializer xmlser = new XmlSerializer(...);
XmlWriterSettings settings = new XmlWriterSettings {Indent = false};
using (XmlWriter xw = XmlWriter.Create(stream, settings))
{
...
Related
I have a XML structer like that
<?xml version="1.0" encoding="utf-8"?>
<Product>
<ProductName>da</ProductName>
<PluginPath></PluginPath>
<Instances></Instances>
</Product>
and i serialize my object to string.
<?xml version="1.0"?>
<Instance xmlns:xsi="http://bla bla" xmlns:xsd="bla bla" UniqueId="d4820029b7d7">
<InstanceName>Instance MyTestPluginForm</InstanceName>
<Description>Test Plugin IW</Description>
<AddedDate>2016-10-19T11:05:10.7443404+02:00</AddedDate>
<LogSettings>
<LoggingLevel>None</LoggingLevel>
<LogFilePath /><MaximumSize>100</MaximumSize
<ClearAfterDays>7</ClearAfterDays>
<IsSaveActiviesToEventLog>false</IsSaveActiviesToEventLog>
</LogSettings>
<ProductSpecific/>
</Instance>
So I want to append the second one in the Instances node in the first xml. But as you see both has xml definition on the top and after serializazion i got xmlns:xsi and xmlns:xsd attributes.
How to solve this problem?
PS: I do not want to create XML elements. Because my xml schema is dynamic. It has to be done with serialization. (I already checked this sample)
I solved the problem. using the code here
public static void CreateXmlFile(Instance instance, string filePath)
{
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Product><ProductName>da</ProductName><PluginPath></PluginPath><Instances></Instances></Product>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
xmlDocument.Save(filePath);
XmlNode xnode = xmlDocument.CreateNode(XmlNodeType.Element, "Instances", null);
XmlSerializer xSeriz = new XmlSerializer(typeof(Instance));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlWriterSettings writtersetting = new XmlWriterSettings();
writtersetting.OmitXmlDeclaration = true;
StringWriter stringwriter = new StringWriter();
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(stringwriter, writtersetting))
{
xSeriz.Serialize(xmlwriter, instance, ns);
}
xnode.InnerXml = stringwriter.ToString();
XmlNode bindxnode = xnode.SelectSingleNode("Instance");
xmlDocument.DocumentElement.SelectSingleNode("Instances").AppendChild(bindxnode);
xmlDocument.Save(filePath);
}
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();
}
I'm using XmlWriter and XmlWriterSettings to write an XML file to disk. However, the system that is parsing the XML file is complaining about the encoding.
<?xml version="1.0" encoding="utf-8"?>
What it wants is this:
<?xml version="1.0" ?>
If I try OmitXmlDeclaration = true, then I don't get the xml line at all.
string destinationName = "C:\\temp\\file.xml";
string strClassification = "None";
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(destinationName, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("ChunkData");
writer.WriteElementString("Classification", strClassification);
writer.WriteEndElement();
}
Just ran into this ---
remove the XmlWriterSettings() altogether and use the XmlTextWriter()'s Formatting field for indention.
pass in null for the Encoding argument of XmlTextWriter's ctor
The following code will create the output that you're looking for:
<?xml version="1.0" ?>
var w = new XmlTextWriter(filename, null);
w.Formatting = Formatting.Indented;
w.WriteStartDocument();
w.WriteStartElement("ChunkData");
w.WriteEndDocument();
w.Close();
The .Close() effectively creates the file - the using and Create() approach will also work.
Is there any way to take an xml string in .net and make it easyer to read?
what i mean is can i convert this:
<element1><element2>some data</element2></element1>
to this:
<element1>
<element2>
some data
</element2>
</element1>
is there any built in class for this? as sql server 2005 seems to remove all formatting on xml to save space or some thing...
If you're using .NET 3.5, you can load it as an XDocument and then just call ToString() which will indent it appropriately. For example:
using System;
using System.Xml.Linq;
public class Test
{
static void Main()
{
string xml = "<element1><element2>some data</element2></element1>";
XDocument doc = XDocument.Parse(xml);
xml = doc.ToString();
Console.WriteLine(xml);
}
}
Result:
<element1>
<element2>some data</element2>
</element1>
If you're writing it to a file or other stream, then XDocument.Save will (by default) indent it too.
(I believe XElement has all the same features, if you don't really need an XDocument.)
How do you save / write the XML back to a file ?
You can create an XmlWriter and pass it an XmlWriterSettings instance, where you set the Indent property to true:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create (outputStream, settings);
You can load the string into an XDocument object and save it to a string again:
XDocument doc = XDocument.Load(new StringReader(xmlString));
StringWriter writer = new StringWriter();
doc.Save(writer);
string readable = writer.ToString();
That will give you the xml formatted this way:
<?xml version="1.0" encoding="utf-16"?>
<element1>
<element2>some data</element2>
</element1>
Have a look at
XmlWriterSettings
http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx
you can define Indent and IndentChars
First of all, you have tagged C# and VB.NET both. So my answer will be for both of them.
You can define function which get XML string as a parameter in type of String.
Let's say;
You created a function as :
[VB]
Private Function PrettyXML(XMLString As String) As String
Dim sw As New StringWriter()
Dim xw As New XMLWriter(sw)
xw.Formatiing = Formatting.Indented
xw.Indentation = 4
Dim doc As New XMLDocument
doc.LoadXML(XMLString)
doc.Save(xw)
Return sw.ToString()
End Function
Then you can simpyl call this function as:
Dim myXML As String = "<element1><element2>some data</element2></element1>"
Dim myPrettyXML As String
myPrettyXML = PrettyXML(myPrettyXML)
[C#]
Private String PrettyXML(string XMLString)
{
StringWriter sw = new StringWriter();
XMLTextWriter xw = new XmlTextWriter(sw);
xw.Formatiing = Formatting.Indented;
xw.Indentation = 4;
XmlDocument doc = new XmlDocument();
doc.Save(xm);
return sw.ToString();
}
Then you can simply call this function as:
string myXML = "<element1><element2>some data</element2></element1>";
string myPrettyXML = "";
myPrettyXML = PrettyXML(myPrettyXML);
NOTE: I have not tried C# version, but it should work.
Hope this helps..
I am editing csproj files with Linq-to-XML and need to save the XML without the <?XML?> header.
As XDocument.Save() is missing the necessary option, what's the best way to do this?
You can do this with XmlWriterSettings, and saving the document to an XmlWriter:
XDocument doc = new XDocument(new XElement("foo",
new XAttribute("hello","world")));
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw, settings))
// or to write to a file...
//using (XmlWriter xw = XmlWriter.Create(filePath, settings))
{
doc.Save(xw);
}
string s = sw.ToString();
A simpler solution than the accepted answer is to use XDocument.ToString() to get the XML text without the header.
Example:
// Load the file
XDocument xDocument = XDocument.Load(fileName);
// Edit the XML...
// Save the edited XML text to file
File.WriteAllText(fileName, xDocument.ToString());