簡體   English   中英

XDocument保存沒有換行符

[英]XDocument saving without line breaks

我正在使用XDocument寫入XML文件。 寫入完成后,XML不再可讀,因為幾乎完全省略了換行符。

XDocument xmlDoc = new XDocument();
XElement xmlRoot = new XElement("root", "root");
XElement xmlEntry = new XElement("file",
   new XAttribute("name", "Example"),
   new XAttribute("hashcode", "Hashcode Example")
);
xmlRoot.Add(xmlEntry);
xmlDoc.Add(xmlRoot);
xmlDoc.Save("C:\\contents.xml");

我已經嘗試了xmlDoc.Save()行的各種選項,包括:

xmlDoc.Save("...", SaveOptions.DisableFormatting);
xmlDoc.Save("...", SaveOptions.None);

請注意,我提交的代碼是程序實際包含的形式的簡化形式; 在功能上是相同的。

上面僅調用xmlDoc.Save("C:\\\\contents.xml")的代碼將xml保存為“漂亮”格式。 它只是沒有按照您期望的方式格式化。 我認為問題是因為您要在同一節點上添加文本值和子節點,所以解析器可能不知道如何或專門不分解這些值。

如果您修改代碼以生成沒有文本值的'root'元素,它將以您可能期望的方式顯示xml。 我用此代碼進行了測試:

        XDocument xmlDoc = new XDocument();
        XElement xmlRoot = new XElement("root");
        XElement xmlEntry = new XElement("file",
           new XAttribute("name", "Example"),
           new XAttribute("hashcode", "Hashcode Example with some long string")
        );
        xmlRoot.Add(xmlEntry);
        xmlDoc.Add(xmlRoot);
        xmlDoc.Save("temp.xml");
        Console.WriteLine(System.IO.File.ReadAllText("temp.xml"));

此代碼可以使用一種更簡潔的方式來生成上述內容,我也認為它更具可讀性:

XDocument xmlDoc = new XDocument();
xmlDoc.Add(
    new XElement("root",
        new XElement("file",
            new XAttribute("name", "example"),
            new XAttribute("hashcode", "hashcode example")
        )
    )
);
xmlDoc.Save("temp.xml");
Console.WriteLine(System.IO.File.ReadAllText("temp.xml"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM