2013-08-29 6 views
12

XDocument'ın varsayılan girintisini 2'den 3'e değiştirmeye çalışıyorum, ancak nasıl devam edeceğimi tam olarak bilmiyorum. Bu nasıl yapılabilir?XDocument ile XML yazarken girinti için kullanılan karakter sayısı nasıl değiştirilir

Ben XmlTextWriter aşina olduğum ve bu şekilde kod kullanmış:

buna benzer benim uygulanması için daha iyi çalışır çünkü XDocument kullanılan başka bir proje için
using System.Xml; 

namespace ConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string destinationFile = "C:\myPath\results.xml"; 
      XmlTextWriter writer = new XmlTextWriter(destinationFile, null); 
      writer.Indentation = 3; 
      writer.WriteStartDocument(); 

      // Add elements, etc 

      writer.WriteEndDocument(); 
      writer.Close(); 
     } 
    } 
} 

: As

using System; 
using System.Collections.Generic; 
using System.Xml.Linq; 
using System.Xml; 
using System.Text; 

namespace ConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Source file has indentation of 3 
      string sourceFile = @"C:\myPath\source.xml"; 
      string destinationFile = @"C:\myPath\results.xml"; 

      List<XElement> devices = new List<XElement>(); 

      XDocument template = XDocument.Load(sourceFile);   

      // Add elements, etc 

      template.Save(destinationFile); 
     } 
    } 
} 
+0

'Kaydet 'XmlWriter'i alır ... - http://msdn.microsoft.com/en-us/library/bb336977.aspx –

cevap

19

@ John Saunders ve @ sa_ddam213, new XmlWriter onaylanmadığı için biraz daha derine kazdım ve XmlWriterSettings kullanarak girintiyi nasıl değiştireceğimi öğrendim. @ Sa_ddam213'den aldığım using bildirimi fikri. Bu bana ihtiyacım 3 uzay girinti verdi

XmlWriterSettings settings = new XmlWriterSettings(); 
settings.Indent = true; 
settings.IndentChars = " "; // Indent 3 Spaces 

using (XmlWriter writer = XmlTextWriter.Create(destinationFile, settings)) 
{      
    template.Save(writer); 
} 

:

aşağıdaki ile template.Save(destinationFile); değiştirilmiştir. Daha fazla boşluk gerekiyorsa, bunları IndentChars'a ekleyin veya "\t" sekme için kullanılabilir.

+0

+1, iyi buluyorum, çok fazla şey alırken benimkini kaldırdım Olumsuz geribildirim ve çözümünüz, eski 'XmlTextWriter 'kullanmanın dışında iyi bir çözümdür. –

İlgili konular