2011-03-29 23 views
2

我想創建一個使用字符串數據(這是一個XML)的XML文件。但主要問題是我創建的xml格式不正確。我已經使用XmlWriterSettings來格式化XML,但它似乎並沒有工作。任何人都可以告訴我這段代碼有什麼問題。XMl的縮進無法按預期工作!

string unformattedXml = @"<datas><data1>sampledata1</data1><datas>"; 

    XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true}; 
    using (XmlWriter writer = XmlWriter.Create(Console.Out, xmlSettingsWithIndentation)) 
     { 

      writer.WriteRaw(unformattedXml); 
     } 

其實當我加載此字符串一個XmlDocument,然後將其保存爲一個文件,這是formatted.I只是想知道爲什麼它不與XmlWriter的工作。

您的幫助將不勝感激。

謝謝 Alex。

+2

我認爲,'縮進= TRUE;不適用於WriteRaw – Andrey 2011-03-29 07:54:10

回答

0

嘿,這段代碼應該這樣做;使用一個XmlReader而不是原始字符串(我希望它是一個錯字,當你的最後一個XML元素是不封閉的物業,並通過格式化你是指正確的縮進):

class Program 
{ 
    static void Main(string[] args) 
    { 
     string unformattedXml = @"<datas><data1>sampledata1</data1></datas>"; 

     XmlReader rdr = XmlReader.Create(new StringReader(unformattedXml)); 

     StringBuilder sb = new StringBuilder(); 

     XmlWriterSettings xmlSettingsWithIndentation = 
      new XmlWriterSettings 
      { 
       Indent = true 
      }; 

     using (XmlWriter writer = XmlWriter.Create(sb, xmlSettingsWithIndentation)) 
     { 
      writer.WriteNode(rdr, true); 
     } 
     Console.WriteLine(sb); 
     Console.ReadKey(); 
    } 
} 

它輸出:

<?xml version="1.0" encoding="utf-16"?> 
<datas> 
    <data1>sampledata1</data1> 
</datas> 

請參閱類似的問題: XmlWriter.WriteRaw indentation XML indenting when injecting an XML string into an XmlWriter

1

忽略空白的嘗試:

private static string FormatXML(string unformattedXml) { 
    // first read the xml ignoring whitespace 
    XmlReaderSettings readeroptions= new XmlReaderSettings {IgnoreWhitespace = true}; 
    XmlReader reader = XmlReader.Create(new StringReader(unformattedXml),readeroptions); 

    // then write it out with indentation 
    StringBuilder sb = new StringBuilder(); 
    XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};      
    using (XmlWriter writer = XmlWriter.Create(sb, xmlSettingsWithIndentation)) { 
     writer.WriteNode(reader, true); 
    } 

    return sb.ToString(); 
}