C# 如何让 xmlserializer 只序列化纯 xml?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1772004/
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
How can I make the xmlserializer only serialize plain xml?
提问by Grzenio
I need to get plain xml, without the <?xml version="1.0" encoding="utf-16"?>
at the beginning and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
in first element from XmlSerializer
. How can I do it?
我需要获取纯 xml,没有<?xml version="1.0" encoding="utf-16"?>
开头和xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
第一个元素来自XmlSerializer
. 我该怎么做?
采纳答案by Simon Sanderson
To put this all together - this works perfectly for me:
把这一切放在一起 - 这对我来说非常有效:
// To Clean XML
public string SerializeToString<T>(T value)
{
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(value.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, emptyNamespaces);
return stream.ToString();
}
}
回答by tobsen
You can use XmlWriterSettingsand set the property OmitXmlDeclarationto true as described in the msdn. Then use the XmlSerializer.Serialize(xmlWriter, objectToSerialize)as described here.
您可以使用XmlWriterSettings并将属性OmitXmlDeclaration设置为 true,如 msdn 中所述。然后使用这里描述的XmlSerializer.Serialize(xmlWriter, objectToSerialize)。
回答by kossib
Use the XmlSerializer.Serialize
method overload where you can specify custom namespaces and pass there this.
使用XmlSerializer.Serialize
方法重载,您可以在其中指定自定义命名空间并将其传递到那里。
var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(xmlWriter, objectToSerialze, emptyNs);
passing null or empty array won't do the trick
传递 null 或空数组不会成功
回答by Keith Aymar
This will write the XML to a file instead of a string. Object ticket is the object that I am serializing.
这会将 XML 写入文件而不是字符串。对象票证是我正在序列化的对象。
Namespaces used:
使用的命名空间:
using System.Xml;
using System.Xml.Serialization;
Code:
代码:
XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlSerializer serializer = new XmlSerializer(typeof(ticket));
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (XmlWriter xmlWriter = XmlWriter.Create(fullPathFileName, settings))
{
serializer.Serialize(xmlWriter, ticket, emptyNamespaces);
}