1

我正在尝试从 C# 中的某些数据中导出 xml

XDocument doc = XDocument.Parse(xml);

保存 XML 后,我发现 XML 包含

<?xml version="1.0" encoding="utf-8"?>

我根本没有输入,并导致如下问题。

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="..\..\dco.xsl"?>
<S>
  <B>
  </B>
</S>

我不希望第一行出现,有什么想法吗?感谢您的回复。

4

3 回答 3

2

如果我理解正确,您需要一个没有标题的 XML 文件。看看这个答案

基本上,您将需要初始化XmlWriterXmlWriterSettings类,然后调用doc.Save(writer).

于 2012-07-03T08:27:17.733 回答
2

它的 PI(处理指令)是处理 xml 文件时需要并包含的重要信息。

在编写 xml 文件时试试这个:

XmlWriter w;
w.Settings = new XmlWriterSettings();
w.Settings.ConformanceLevel = ConformanceLevel.Fragment;
w.Settings.OmitXmlDeclaration = true;

序列化对象时省略 XML 处理指令

从 xml 文件中删除版本

http://en.wikipedia.org/wiki/Processing_Instruction

于 2012-07-03T08:30:20.247 回答
2

您所说的是“之后”,您使用字符串解析,如您在上面看到的结果包含重复声明?

现在我不确定您如何保存您的回复,但这里有一个示例应用程序,它会产生类似的结果。

XDocument doc = XDocument.Parse("<?xml-stylesheet type=\"text/xsl\" href=\"dco.xsl\"?><S><B></B></S>");
            doc.Save(Console.OpenStandardOutput());

产生结果:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dco.xsl"?>
<S>
  <B></B>
</S>

这是你遇到的问题。您需要在保存之前删除 xml 声明。这可以通过在保存 xml 输出时使用 xml 编写器来完成。这是一个示例应用程序,它带有一个扩展方法,可以在没有声明的情况下编写新文档。

class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse("<?xml-stylesheet type=\"text/xsl\" href=\"dco.xsl\"?><S><B></B></S>");
            doc.SaveWithoutDeclaration(Console.OpenStandardOutput());
            Console.ReadKey();
        }


    }

    internal static class Extensions
    {
        public static void SaveWithoutDeclaration(this XDocument doc, string FileName)
        {
            using(var fs = new StreamWriter(FileName))
            {
                fs.Write(doc.ToString());
            }
        }

        public static void SaveWithoutDeclaration(this XDocument doc, Stream Stream)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(doc.ToString());
            Stream.Write(bytes, 0, bytes.Length);
        }
    }
于 2012-07-03T08:54:20.893 回答