AEMLoviji
AEMLoviji

Reputation: 3257

C# XML serialization

I want simple XML as :

>  <?xml version="1.0" encoding="utf-8" ?>
>     <contacts>
>       <contact>   
>         <mobile>0555555555</mobile>
>         <home>4212566</home>
>         <office>45698752</office>    
>         <fax>090909</fax>  
>         <email>[email protected]</email>  
>       </contact> 
>       ................................
>       <contact>   
>         <mobile>0555555555</mobile>
>         <home>4212566</home>
>         <office>45698752</office>    
>         <fax>090909</fax>  
>         <email>[email protected]</email>  
>       </contact>
>     </contacts>

i used sample from link text

all work fine but there has some attributes such as xmlns:xsi and xmlns:xsd. i dont want to save it on my xml. and dont want to use Replace methods How do it?

I will use it in MVC Application. What is the best way to create an xml on memory? And look this post link text when going to answer

Upvotes: 0

Views: 834

Answers (2)

jgauffin
jgauffin

Reputation: 101130

To omit XML declaration and default XML namespaces:

var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };

var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);

using (var writer = XmlWriter.Create(file, settings))
{
    XmlSerializer serializer = new XmlSerializer(source.GetType());
    serializer.Serialize(writer, source, namespaces);
}

Upvotes: 2

Tim Robinson
Tim Robinson

Reputation: 54714

Initialize your XmlWriter with an XmlWriterSettings, and set XmlWriterSettings.OmitXmlDeclaration to true:

XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter writer = XmlWriter.Create(textWriter, settings))
{
    // serialize XML here
}

Upvotes: 3

Related Questions