我有一個XDocument對象,並且ToString()方法返回沒有任何縮進的XML。如何從包含縮進的XML創建一個字符串?如何從C#中的XDocument創建縮進的XML字符串?
編輯:我問如何創建一個內存字符串,而不是寫出一個文件。
編輯:看起來像我不小心問了一個技巧問題在這裏... ToString()確實返回縮進的XML。
我有一個XDocument對象,並且ToString()方法返回沒有任何縮進的XML。如何從包含縮進的XML創建一個字符串?如何從C#中的XDocument創建縮進的XML字符串?
編輯:我問如何創建一個內存字符串,而不是寫出一個文件。
編輯:看起來像我不小心問了一個技巧問題在這裏... ToString()確實返回縮進的XML。
XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();
這工作正常。 'XDocument.ToString()'默認使用縮進格式。爲了得到未格式化的輸出,你必須通過調用'.ToString(SaveOptions.DisableFormatting)' –
來實現查找禁用。謝謝@JoelMueller – Eric
從here
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
問題是如何創建一個字符串,而不是如何創建一個文件。 –
@JC:在XmlTextWriter的構造函數中使用StringWriter而不是文件名來獲取字符串。 –
-1:不要使用'new new XmlTextWriter()'或'new XmlTextReader()'過去.NET 1.1。使用'XmlWriter.Create()'或'XmlReader.Create()'。 –
要使用一個XDocument(而不是一個XmlDocument)創建一個字符串,你可以使用:
XDocument doc = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2")
)
);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlTextWriter.Create(sb, settings)) {
doc.WriteTo(writer);
writer.Flush();
}
string outputXml = sb.ToString();
編輯:更新使用XmlWriter.Create
和StringBuilder
和良好的形式(using
)。
-1:不要使用新的XmlTextWriter()或新的XmlTextReader()通過.NET 1.1。使用XmlWriter.Create()或XmlReader.Create() –
謝謝,我錯過了。我相應地更新了示例(並且同時使用StringBuilder降低了複雜性!) – DocMax
僅供參考,在審閱時,我仍然希望保留我的downvote,因爲您沒有使用'using'塊。 –
只是一個同樣的湯更有味道... ;-)
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
Console.WriteLine(sw.ToString());
編輯:感謝John Saunders。這是一個應該更好地符合Creating XML Writers on MSDN的版本。
using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
XDocument doc = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2")
)
);
var builder = new StringBuilder();
var settings = new XmlWriterSettings()
{
Indent = true
};
using (var writer = XmlWriter.Create(builder, settings))
{
doc.WriteTo(writer);
}
Console.WriteLine(builder.ToString());
}
}
喜歡這個給我,但你的用途在哪裏? – tomfanning
-1:不要使用新的XmlTextWriter()或新的XmlTextReader()通過.NET 1.1。使用XmlWriter.Create()或XmlReader.Create() –
您可以發佈您的代碼?我可以讓XDocument.ToString不縮進XML的唯一方法是當我將SaveOptions.DisableFormatting傳遞給ToString方法時。 –
我在這裏試過了答案。他們沒有效果(仍然使用空格)。使用.Net 4(不是客戶端)。 –
相關:http://stackoverflow.com/questions/1123718/format-xml-string-to-print-friendly-xml-string – CJBS