.net – 序列化为XML片段 – 而不是XML文档

前端之家收集整理的这篇文章主要介绍了.net – 序列化为XML片段 – 而不是XML文档前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将 XML序列化对象序列化为 XML片段(根元素中没有XML声明或命名空间引用)?
这是一个hack-ish的方法,而不必将整个输出字符串加载到XmlDocument中:
  1. using System;
  2. using System.Text;
  3. using System.Xml;
  4. using System.Xml.Serialization;
  5.  
  6. public class Example
  7. {
  8. public String Name { get; set; }
  9.  
  10. static void Main()
  11. {
  12. Example example = new Example { Name = "Foo" };
  13.  
  14. XmlSerializer serializer = new XmlSerializer(typeof(Example));
  15.  
  16. XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
  17. emptyNamespace.Add(String.Empty,String.Empty);
  18.  
  19. StringBuilder output = new StringBuilder();
  20.  
  21. XmlWriter writer = XmlWriter.Create(output,new XmlWriterSettings { OmitXmlDeclaration = true });
  22. serializer.Serialize(writer,example,emptyNamespace);
  23.  
  24. Console.WriteLine(output.ToString());
  25. }
  26. }

猜你在找的XML相关文章