2011-06-06 40 views
0

下面的代碼導致「根數據無效,第1行,位置1」。 我喜歡讓代碼縮進(換行符),但始終將問題保留爲上文提到的。我可以使用TextReader加載XML,但它會刪除我不喜歡的縮進。如果你知道如何解決問題,請讓我知道。謝謝C#XML無法加載縮進值

public XmlDocument MYXML() 
    { 
    XmlWriterSettings wSettings = new XmlWriterSettings(); 
     wSettings.Indent = false; 
     wSettings.OmitXmlDeclaration = false; 
     MemoryStream ms = new MemoryStream(); 
     XmlWriter xw = XmlWriter.Create(ms, wSettings);// Write Declaration 
     xw.WriteStartDocument(); 

     // Write the root node 
     xw.WriteStartElement("Library"); 

     // Write the books and the book elements 
     xw.WriteStartElement("Book"); 
     xw.WriteStartAttribute("BookType"); 
     xw.WriteString("Hardback"); 
     xw.WriteEndAttribute(); 

     xw.WriteStartElement("Title"); 
     xw.WriteString("Door Number Three"); 
     xw.WriteEndElement(); 
     xw.WriteStartElement("Author"); 
     xw.WriteString("O'Leary, Patrick"); 
     xw.WriteEndElement(); 

     xw.WriteEndElement(); 

     xw.WriteEndElement(); 

     // Close the document 
     xw.WriteEndDocument(); 

     // Flush the write 
     xw.Flush(); 

     Byte[] buffer = new Byte[ms.Length]; 
     buffer = ms.ToArray(); 
     string xmlOutput = System.Text.Encoding.UTF8.GetString(buffer); 

     //The next 3 line works fine but it will remove the Indent from the XmlWriterSettings 
     //TextReader tr = new StreamReader(ms); 
     //ms.Seek(0, SeekOrigin.Begin); 
     //xmlOutput = tr.ReadToEnd() + ""; 

     //Can't nload the xmlOutput from buffer 
     XmlDocument xmldoc = new XmlDocument(); 
     xmldoc.LoadXml(xmlOutput); 

     return xmldoc; 
    } 
+0

整個編碼往返的目的是什麼? – Jodrell 2011-06-06 13:27:07

+0

我真的需要將XML加載到XMLDocument中,因爲我需要返回XmlDocument,以便它可以在多個區域重複使用並使其更易於操作 – SMTPGUY01 2011-06-06 13:33:03

回答

1

XmlWriter正在寫一個UTF-8字節順序標記到流中。 Encoding.UTF8.GetString沒有考慮到這一點(因爲它只發生在文件中),所以字符串的第一個字符變成了一個無效的,不可打印的字符,這就是XmlDocument.LoadXml扼殺的內容。

編輯:既然你說你想創建一個XmlDocument,所以你可以重複使用它,我建議下列之一:

  1. 如果使用.net 3.5或更新版本,使用XDocument這是非常容易使用(我推薦這個)。
  2. 通過構建節點並將它們添加到樹中直接創建XmlDocument。
  3. 從筆者使用的XPathNavigator(XmlWriter writer = doc.CreateNavigator.AppendChild()

需要注意的是,你不能輕易添加不重要的空白,以一個XmlDocument直接創建的XmlDocument。使用XDocument並使用doc.Save(Response.Output)將其寫入輸出是迄今爲止最簡單的選擇,如果您想要格式良好的輸出。

+0

我確實需要將XML加載到XMLDocument中,因爲我需要返回XmlDocument,因此可以在多個區域重用,並使其更易於操作。 – SMTPGUY01 2011-06-06 13:32:36

+0

在這種情況下,通過創建節點並添加子節點直接創建'XmlDocument'。或者,如果這是.Net 3.5和更新版本,請使用'XDocument',而不是更容易處理。首先將其寫入一個字符串然後再解析它是非常浪費的(儘管爲了將來的參考,如果您必須將XML寫入字符串,請不要使用「MemoryStream」,創建一個寫入「StringBuilder」的「XmlWriter」或'StringWriter'來代替,但是我再次不推薦這樣做)。 – Sven 2011-06-06 13:36:07