我的XDeclaration在哪里?

时间:2011-06-07 18:26:28

标签: c# .net xml linq-to-xml

由于某种原因,以下代码生成的XML不包含声明:

        XDocument xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("project",
                new XAttribute("number", project.ProjectNumber),
                new XElement("store",
                    new XAttribute("number", project.StoreNumber)
                ),

                // User Element
                new XElement("user", 
                    new XAttribute("owner-id", project.OwnerID ?? 0),
                    new XElement("email", new XCData(project.OwnerEmail ?? "")),
                    new XElement("project-name", new XCData(project.ProjectName ?? ""))
                ),

                // Nested Project Element
                new XElement("nested-project", 
                    new XAttribute("version", new Version(1, 0)),
                    new XElement("project", 
                        new XAttribute("version", new Version(1, 0)),
                        xProjectItems = new XElement("project-items")
                    ),
                    new XElement("price-per-part", project.PricePerPart),
                    new XElement("sheet-quantity", project.SheetQuantity),
                    new XElement("edge-length", project.EdgeLength),
                    new XElement("price", project.Price),
                    new XElement("status", project.Status),
                    xMaterialItems = new XElement("alternative-material-items"),
                    xProductItems = new XElement("project-product-items")
                )
            )
        );

        String strXML = xDocument.ToString();

之前已经发表了声明。我错过了一些明显的东西吗

感谢。

3 个答案:

答案 0 :(得分:26)

当您使用XDocument.Save methods之一时,XDeclaration将可用。例如:

var doc = new XDocument (
            new XDeclaration ("1.0", "utf-8", "yes"),
            new XElement ("test", "data")
        );

string path = Path.Combine(Path.GetTempPath(), "temp.xml");
doc.Save(path);
Console.WriteLine(File.ReadAllText(path));

或者你可以使用这种方法:

var sw = new StringWriter();
doc.Save(sw);
string result = sw.GetStringBuilder().ToString();
Console.WriteLine(result);

编辑:请注意,某些方法会将utf-8指定转换为utf-16。如果你想强制它为utf-8,你将不得不使用这种不同的方法:

using (var mem = new MemoryStream())  
using (var writer = new XmlTextWriter(mem, System.Text.Encoding.UTF8))
{
    writer.Formatting = Formatting.Indented;
    doc.WriteTo(writer);
    writer.Flush();
    mem.Flush();
    mem.Seek(0, SeekOrigin.Begin);
    using (var reader = new StreamReader(mem))
    {
        var xml = reader.ReadToEnd();
        Console.WriteLine(xml);
    }
}

答案 1 :(得分:3)

documentation没有明确声明xDocument.ToString()将输出XML声明,它只说:“返回此节点的缩进XML。”。

在我的测试中,我发现以下方法将输出声明:

ToString媒体资源上使用Declaration

string strXML = string.Concat(xDocument.Declaration.ToString(), "\r\n",
                              xDocument.ToString());

或使用Save方法:

string strXml;
using(var ms = new MemoryStream())
{
    xDocument.Save(ms);
    ms.Position = 0;
    using(var sr = new StreamReader(ms))
    {
        strXml = sr.ReadToEnd();
    }
}

答案 2 :(得分:2)

我的回答(灵感来自the answer by @rsbarro):

string xml = xDocument.Declaration.ToString() +
    xDocument.ToString();

- 或 -

string xml = xDocument.Declaration.ToString() +
    xDocument.ToString(SaveOptions.DisableFormatting);

至于为什么我认为在这种情况下使用+运算符是合适的,请参阅问题this answerWhat's the best string concatenation method using C#?