使用Mono版本2.10.5,以下代码在任何XML文档上都失败:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Linq;
namespace TestXDocument
{
class MainClass
{
public static void Main (string[] args)
{
Stream s = File.Open("Settings.xml", FileMode.Open);
XDocument d = XDocument.Load(s, LoadOptions.PreserveWhitespace);
s.Close();
d.Save("Settings.xml");
}
}
}
仅当XDocument.Load使用LoadOptions.PreserveWhitespace时才会发生这种情况。关于如何解决这个问题或解决问题的任何想法?
在Linux Mint 12和Ubuntu 11.10上测试。
以下是例外:
Unhandled Exception: System.InvalidOperationException: This XmlWriter does not accept Text at this state Prolog.
at System.Xml.XmlTextWriter.ShiftStateContent (System.String occured, Boolean allowAttribute) [0x00000] in <filename unknown>:0
at System.Xml.XmlTextWriter.WriteString (System.String text) [0x00000] in <filename unknown>:0
at System.Xml.DefaultXmlWriter.WriteString (System.String text) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XText.WriteTo (System.Xml.XmlWriter w) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.WriteTo (System.Xml.XmlWriter w) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Save (System.Xml.XmlWriter w) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Save (System.String filename, SaveOptions options) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Save (System.String filename) [0x00000] in <filename unknown>:0
at TestXDocument.MainClass.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: This XmlWriter does not accept Text at this state Prolog.
at System.Xml.XmlTextWriter.ShiftStateContent (System.String occured, Boolean allowAttribute) [0x00000] in <filename unknown>:0
at System.Xml.XmlTextWriter.WriteString (System.String text) [0x00000] in <filename unknown>:0
at System.Xml.DefaultXmlWriter.WriteString (System.String text) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XText.WriteTo (System.Xml.XmlWriter w) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.WriteTo (System.Xml.XmlWriter w) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Save (System.Xml.XmlWriter w) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Save (System.String filename, SaveOptions options) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Save (System.String filename) [0x00000] in <filename unknown>:0
at TestXDocument.MainClass.Main (System.String[] args) [0x00000] in <filename unknown>:0
答案 0 :(得分:3)
我可以在Ubuntu 11.10的两个代码示例中重现相同的问题。正如您所说,在Windows平台上没有问题。似乎Mono运行时在XDocument的Save方法中存在某些错误,从而导致意外错误。我想向Mono运行时团队报告此问题以获取软件补丁。
但是,我可以带来的可能的解决方法是,
d.Root.Save("Settings1.xml");
似乎XElement中的Save方法没有我们在XDocument中遇到的任何问题。