C# 格式化由 DataContractSerializer 创建的 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/739114/
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
Formatting of XML created by DataContractSerializer
提问by Eric Anastas
Is there an easy way to get DataContractSerializer to spit out formatted XML rather then one long string? I don't want to change the tags or content in any way, just have it add line breaks and indentation to make the XML more readable?
有没有一种简单的方法可以让 DataContractSerializer 吐出格式化的 XML 而不是一个长字符串?我不想以任何方式更改标签或内容,只需添加换行符和缩进以使 XML 更具可读性?
<tagA>
<tagB>This is</tagB>
<tagC>Much</tagC>
<tagD>
<tagE>easier to read</tagE>
</tagD>
</tagA>
<tagA><tagB>This is</tagB><tagC>Much</tagC><tagD><tagE>harder to read</tagE></tagD></tagA>
采纳答案by Steve Willcock
As bendewey says, XmlWriterSettings is what you need - e.g. something like
正如本德威所说, XmlWriterSettings 是您所需要的 - 例如
var ds = new DataContractSerializer(typeof(Foo));
var settings = new XmlWriterSettings { Indent = true };
using (var w = XmlWriter.Create("fooOutput.xml", settings))
ds.WriteObject(w, someFoos);
回答by bendewey
Take a look at the Indent
property of the XmlWriterSettings
看看楼主的Indent
属性XmlWriterSettings
Update:Here is a good link from MSDN on How to: Specify the Output format on the XmlWriter
更新:这是 MSDN 上关于如何:在 XmlWriter 上指定输出格式的一个很好的链接
Additionally, here is a sample:
此外,这里有一个示例:
class Program
{
static void Main(string[] args)
{
var Mark = new Person()
{
Name = "Mark",
Email = "[email protected]"
};
var serializer = new DataContractSerializer(typeof(Person));
var settings = new XmlWriterSettings()
{
Indent = true,
IndentChars = "\t"
};
using (var writer = XmlWriter.Create(Console.Out, settings))
{
serializer.WriteObject(writer, Mark);
}
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
}
回答by Amit Bagga
public static string SerializeEntity<T>(T source)
{
using (MemoryStream ms = new MemoryStream())
{
NetDataContractSerializer serializer = new NetDataContractSerializer();
serializer.Serialize(ms, source);
return System.Text.Encoding.ASCII.GetString(ms.ToArray());
}
}
public static T DeSerializeEntity<T>(string xml)
{
using (MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(xml)))
{
NetDataContractSerializer serializer = new NetDataContractSerializer();
return (T)serializer.Deserialize(ms);
}
}
回答by dthrasher
Be careful about adjusting whitespace in XML documents! Adjusting whitespace will make the XML more readable for us humans, but it may interfere with machine parsing.
小心调整 XML 文档中的空格!调整空白将使 XML 对我们人类更具可读性,但它可能会干扰机器解析。
According to the XML standard, whitespace is significant by default. In other words, as far as XML is concerned, white space is content.
根据XML 标准,默认情况下空格很重要。换句话说,就 XML 而言,空白就是内容。
If you feed your nicely formatted XML into an XML Document object, you will get a different result than the version that has no spaces or line breaks in it. You will get additional text nodes added to the version that has been formatted.
如果您将格式良好的 XML 提供给 XML Document 对象,您将获得与其中没有空格或换行符的版本不同的结果。您将在已格式化的版本中添加额外的文本节点。
This MSDN article on XML White Spacehas several examples that show how tricky white space can be.
这篇关于XML 空白的MSDN 文章有几个例子展示了空白是多么棘手。
If you're formatting the XML only for human consumption, it doesn't matter. But if you try to round-trip your formatted document, you could run into trouble.
如果您只为人类使用而格式化 XML,则没有关系。但是,如果您尝试往返格式化文档,则可能会遇到麻烦。
Since one of the key primary benefits of using DataContractSerializer is the ability to serialize objects and deserialize XML seamlessly, it's usually best to leave the ugly output alone.
由于使用 DataContractSerializer 的主要好处之一是能够无缝地序列化对象和反序列化 XML ,因此通常最好不要理会丑陋的输出。
I usually paste the output into NotePad++ and run an XML-tidy macro over it when I want to read it for debugging purposes.
我通常将输出粘贴到 NotePad++ 中,并在我想读取它以进行调试时在其上运行一个 XML 整洁的宏。
回答by George Birbilis
based on the other samples posted here that use XmlWriter, here's a version (from http://ClipFlair.codeplex.com) that works with streams (and Ionic.Zip library in specific) and also shows how the code is when you don't apply formatting (using conditional compilation - just comment out the #define to make it write unformatted XML)
基于此处发布的使用 XmlWriter 的其他示例,这里有一个版本(来自http://ClipFlair.codeplex.com)适用于流(和特定的 Ionic.Zip 库),并且还显示了代码在您不这样做时的情况t 应用格式(使用条件编译 - 只需注释掉 #define 以使其写入未格式化的 XML)
#define WRITE_FORMATTED_XML
using System.Xml;
namespace ClipFlair.Windows
{
public partial class BaseWindow : FloatingWindow
{
//...
#if WRITE_FORMATTED_XML
private static XmlWriterSettings XML_WRITER_SETTINGS = new XmlWriterSettings() { Indent=true, IndentChars=" "};
#endif
//...
public virtual void SaveOptions(ZipFile zip, string zipFolder = "") //THIS IS THE CORE SAVING LOGIC
{
if (SavingOptions != null) SavingOptions(this, null); //notify any listeners
View.Busy = true;
try
{
ZipEntry optionsXML = zip.AddEntry(zipFolder + "/" + View.GetType().FullName + ".options.xml",
new WriteDelegate((entryName, stream) =>
{
DataContractSerializer serializer = new DataContractSerializer(View.GetType()); //assuming current View isn't null
#if WRITE_FORMATTED_XML
using (XmlWriter writer = XmlWriter.Create(stream, XML_WRITER_SETTINGS))
serializer.WriteObject(writer, View);
#else
serializer.WriteObject(stream, View);
#endif
}));
}
catch (Exception e)
{
MessageBox.Show("ClipFlair options save failed: " + e.Message); //TODO: find the parent window
}
finally
{
View.Busy = false; //in any case (error or not) clear the Busy flag
}
if (SavedOptions != null) SavedOptions(this, null); //notify any listeners
}
//...
}
}