问题描述
我有这样的一些代码,其中序列化对象到一个文件。我试图让每个XML属性输出在单独一行。代码如下:
公共静态无效ToXMLFile(obj对象,字符串文件路径)
{
XmlSerializer的序列化=新的XmlSerializer(obj.GetType());
XmlWriterSettings设置=新XmlWriterSettings();
settings.NewLineOnAttributes = TRUE;
XmlTextWriter的作家=新的XmlTextWriter(文件路径,Encoding.UTF8);
writer.Settings =设置; //这里失败。属性为只读。使用(流baseStream = writer.BaseStream)
{
serializer.Serialize
(作家,OBJ);
}
}
唯一的问题是,在在
属性是只读的。 的XmlTextWriter
对象设置
如何设置设置
在的XmlTextWriter
对象,使 NewLineOnAttributes
设置是否行得通呢?
好吧,我想我需要一个的XmlTextWriter
,因为的XmlWriter
是摘要
类。如果你问我有点困惑。的最后的工作代码是在这里:的
///<总结>
///序列化对象到XML文件;写每个XML属性到一个新行。
///< /总结>
公共静态无效ToXMLFile(obj对象,字符串文件路径)
{
XmlSerializer的序列化=新的XmlSerializer(obj.GetType());
XmlWriterSettings设置=新XmlWriterSettings();
settings.Indent = TRUE;
settings.NewLineOnAttributes = TRUE;使用(XmlWriter的作家= XmlWriter.Create(文件路径,设置))
{
serializer.Serialize
(作家,OBJ);
}
}
使用静态创建()
的XmlWriter
。
的方法
XmlWriter.Create(文件路径,设置);
请注意,您可以设置 NewLineOnAttributes
属性在设置
I have this bit of code, which serializes an object to a file. I'm trying to get each XML attribute to output on a separate line. The code looks like this:
public static void ToXMLFile(Object obj, string filePath)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.NewLineOnAttributes = true;
XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
writer.Settings = settings; // Fails here. Property is read only.
using (Stream baseStream = writer.BaseStream)
{
serializer.Serialize(writer, obj);
}
}
The only problem is, the Settings
property of the XmlTextWriter
object is read-only.
How do I set the Settings
property on the XmlTextWriter
object, so that the NewLineOnAttributes
setting will work?
Well, I thought I needed an XmlTextWriter
, since XmlWriter
is an abstract
class. Kinda confusing if you ask me. Final working code is here:
/// <summary>
/// Serializes an object to an XML file; writes each XML attribute to a new line.
/// </summary>
public static void ToXMLFile(Object obj, string filePath)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
using (XmlWriter writer = XmlWriter.Create(filePath, settings))
{
serializer.Serialize(writer, obj);
}
}
Use the static Create()
method of XmlWriter
.
XmlWriter.Create(filePath, settings);
Note that you can set the NewLineOnAttributes
property in the settings.
这篇关于如何设置在XmlTextWriter的设置属性,让我可以写上自己的行每个XML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!