Mono-XDocument.Load因LoadOptions.PreserveWhitespace而失败
本文关键字:失败 PreserveWhitespace LoadOptions Load Mono-XDocument | 更新日期: 2023-09-27 18:22:47
使用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
我可以在Ubuntu 11.10的两个代码示例中重现相同的问题。正如你所说,Windows平台上没有问题。Mono运行时似乎在XDocument的Save方法中存在某些错误,从而导致意外错误。我想向Mono运行时团队报告这个问题,以获得软件补丁。
然而,我可以在这里提出的可能的解决方案是,
d.Root.Save("Settings1.xml");
XElement中的Save方法似乎没有我们在XDocument中遇到的任何问题。