让我可以写上自己的行每个XML属性

让我可以写上自己的行每个XML属性

本文介绍了如何设置在XmlTextWriter的设置属性,让我可以写上自己的行每个XML属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的一些代码,其中序列化对象到一个文件。我试图让每个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属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:09