gpt4 book ai didi

c# - 序列化对象时省略 XML 处理指令

转载 作者:可可西里 更新时间:2023-11-01 08:59:04 26 4
gpt4 key购买 nike

我在 C# VS2003/.Net 1.1 应用程序中序列化一个对象。但是,我需要在没有处理指令的情况下对其进行序列化。 XmlSerializer 类输出如下内容:

<?xml version="1.0" encoding="utf-16" ?> 
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>

有没有办法得到类似下面的东西,而不用处理结果文本来删除标签?

<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>

对于那些好奇的人,我的代码看起来像这样......

XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();

using ( TextWriter stringWriter = new StringWriter(builder) )
{
serializer.Serialize(stringWriter, comments);
return builder.ToString();
}

最佳答案

我做了一个小修正

XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using ( XmlWriter stringWriter = XmlWriter.Create(builder, settings) )
{
serializer.Serialize(stringWriter, comments);
return builder.ToString();
}

关于c# - 序列化对象时省略 XML 处理指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/164585/

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