簡體   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