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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/164585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:22:01  来源:igfitidea点击:

Omitting XML processing instruction when serializing an object

c#.netxml-serializationvisual-studio-2003

提问by Dan R

I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this:

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

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

Is there any way to get something like the following, without processing the resulting text to remove the tag?

有没有办法得到类似下面的内容,而不处理结果文本以删除标签?

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

For those that are curious, my code looks like this...

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

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

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

采纳答案by DaveK

The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written.

以下链接将带您到一个帖子,其中有人有一种方法可以通过使用 XmlWriter 来抑制处理指令并进入“元素”状态而不是“开始”状态。这导致处理指令不被写入。

Suppress Processing Instruction

抑制处理指令

If you pass an XmlWriter to the serializer, it will only emit a processing instruction if the XmlWriter's state is 'Start' (i.e., has not had anything written to it yet).

如果您将 XmlWriter 传递给序列化程序,则它只会在 XmlWriter 的状态为“开始”(即尚未写入任何内容)时发出处理指令。

// Assume we have a type named 'MyType' and a variable of this type named 
'myObject' 
System.Text.StringBuilder output = new System.Text.StringBuilder(); 
System.IO.StringWriter internalWriter = new System.IO.StringWriter(output); 
System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(internalWriter); 
System.Xml.Serialization.XmlSerializer serializer = new 
System.Xml.Serialization.XmlSerializer(typeof(MyType)); 


writer.WriteStartElement("MyContainingElement"); 
serializer.Serialize(writer, myObject); 
writer.WriteEndElement(); 

In this case, the writer will be in a state of 'Element' (inside an element) so no processing instruction will be written. One you finish writing the XML, you can extract the text from the underlying stream and process it to your heart's content.

在这种情况下,写入器将处于“元素”状态(元素内部),因此不会写入处理指令。编写完 XML 后,您可以从底层流中提取文本并将其处理为您想要的内容。

回答by Marc Gravell

In 2.0, you would use XmLWriterSettings.OmitXmlDeclaration, and serialize to an XmlWriter - however I don't think this exists in 1.1; so not entirelyuseful - but just one more "consider upgrading" thing... and yes, I realise it isn't always possible.

在 2.0 中,您将使用XmLWriterSettings.OmitXmlDeclaration并序列化为 XmlWriter - 但是我认为这在 1.1 中不存在;所以并不完全有用 - 但只是一个“考虑升级”的事情......是的,我意识到这并不总是可能的。

回答by harpo

If by "processing instruction" you mean the xml declaration, then you can avoid this by setting the OmitXmlDeclaration property of XmlWriterSettings. You'll need to serialize using an XmlWriter, to accomplish this.

如果“处理指令”指的是 xml 声明,那么您可以通过设置 XmlWriterSettings 的 OmitXmlDeclaration 属性来避免这种情况。您需要使用 XmlWriter 进行序列化以完成此操作。

XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

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

But ah, this doesn't answer your question for 1.1. Well, for reference to others.

但是啊,这不能回答您对 1.1 的问题。嗯,供他人参考。

回答by DaveK

I made a small correction

我做了一个小更正

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

回答by Cheeso

This works in .NET 1.1. (But you should still consider upgrading)

这适用于 .NET 1.1。(但你还是应该考虑升级)

    XmlSerializer s1= new XmlSerializer(typeof(MyClass)); 
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add( "", "" );


    MyClass c= new MyClass();
    c.PropertyFromDerivedClass= "Hallo";

    sw = new System.IO.StringWriter();
    s1.Serialize(new XTWND(sw), c, ns);
    ....

   /// XmlTextWriterFormattedNoDeclaration
   /// helper class : eliminates the XML Documentation at the
   /// start of a XML doc. 
   /// XTWFND = XmlTextWriterFormattedNoDeclaration
   public class XTWFND : System.Xml.XmlTextWriter
   {
     public XTWFND(System.IO.TextWriter w) : base(w) { Formatting = System.Xml.Formatting.Indented; }
     public override void WriteStartDocument() { }
   }

回答by NetSide

What about omitting namespaces ?

省略命名空间怎么样?

instead of using

而不是使用

XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "");

ex:

前任:

<message xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">