gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:41:31 24 4
gpt4 key购买 nike

如何将 XML 可序列化对象序列化为 XML 片段(根元素中没有 XML 声明或命名空间引用)?

最佳答案

这是一种无需将整个输出字符串加载到 XmlDocument 中的 hack-ish 方法:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class Example
{
public String Name { get; set; }

static void Main()
{
Example example = new Example { Name = "Foo" };

XmlSerializer serializer = new XmlSerializer(typeof(Example));

XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
emptyNamespace.Add(String.Empty, String.Empty);

StringBuilder output = new StringBuilder();

XmlWriter writer = XmlWriter.Create(output,
new XmlWriterSettings { OmitXmlDeclaration = true });
serializer.Serialize(writer, example, emptyNamespace);

Console.WriteLine(output.ToString());
}
}

关于.net - 序列化为 XML 片段 - 而不是 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2768432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com