繁体   English   中英

C#XML序列化

[英]C# XML serialization

我想要简单的XML为:

>  <?xml version="1.0" encoding="utf-8" ?>
>     <contacts>
>       <contact>   
>         <mobile>0555555555</mobile>
>         <home>4212566</home>
>         <office>45698752</office>    
>         <fax>090909</fax>  
>         <email>sdgdg@dgsdg.com</email>  
>       </contact> 
>       ................................
>       <contact>   
>         <mobile>0555555555</mobile>
>         <home>4212566</home>
>         <office>45698752</office>    
>         <fax>090909</fax>  
>         <email>sdgdg@dgsdg.com</email>  
>       </contact>
>     </contacts>

我使用了链接文本中的示例

一切正常,但有一些属性,例如xmlns:xsi和xmlns:xsd。 我不想将其保存在我的xml中。 不想使用Replace方法怎么做?

我将在MVC应用程序中使用它。 在内存上创建xml的最佳方法是什么? 并在回答时查看此帖子链接文本

使用XmlWriter初始化XmlWriterSettings ,并将XmlWriterSettings.OmitXmlDeclaration设置为true

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

要省略XML声明默认的XML名称空间:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM