2016-12-15 69 views
2

問題
在我的多行字符串文字xml的開頭應該忽略空格嗎?IgnoreWhiteSpace不忽略xml開始處的空白字符串

代碼

string XML = @" 
      <?xml version=""1.0"" encoding=""utf-8"" ?>" 

using (StringReader stringReader = new StringReader(XML)) 
using (XmlReader xmlReader = XmlReader.Create(stringReader, 
    new XmlReaderSettings() { IgnoreWhitespace = true })) 
      { 
       xmlReader.MoveToContent(); 
       // further implementation withheld 
      } 

在上面的代碼中有XML聲明前的空白的通知,這似乎並不儘管我的IgnoreWhiteSpace屬性的設置將被忽略。我哪裏錯了?

注意:如果XML字符串沒有換行符,並且只是一個空白符,則具有相同的行爲,如下所示。我知道這將運行,如果我刪除空白,我的問題是爲什麼財產不照顧這個?

string XML = @" <?xml version=""1.0"" encoding=""utf-8"" ?>" 
+1

做到這一點使用(StringReader stringReader =新StringReader(XML.Trim())),以除去白色空格 – rashfmnb

+0

的[ignoreWhitespace屬性(https://msdn.microsoft.com/en-us/library/ system.xml.xmlreadersettings.ignorewhitespace(v = vs.110).aspx)設置不會影響混合內容模式下標記之間的空白或xml:space ='preserve'屬性範圍內出現的空白空間。 – RamblinRose

+0

@RamblinRose謝謝,我在MSDN上看到了。什麼是「混合內容模式」? –

回答

0

本細則說,IgnoreWhitespace屬性將「獲取或設置指示是否忽略微不足道白色空間中的值。」雖然第一個空格(也是linebreak)應該是微不足道的,但是製作XmlReader的人顯然不這麼認爲。在使用前修剪XML,你就會好起來的。

正如評論和清晰說明,更改您的代碼:

string XML = @"<?xml version=""1.0"" encoding=""utf-8"" ?>" 

using (StringReader stringReader = new StringReader(XML.Trim())) 
using (XmlReader xmlReader = XmlReader.Create(stringReader, 
new XmlReaderSettings() { IgnoreWhitespace = true })) 
     { 
      xmlReader.MoveToContent(); 
      // further implementation withheld 
     } 
+0

謝謝,我知道如何糾正它,讓它運行。我正在尋找的是IgnoreWhiteSpace屬性的界限,以及爲什麼在這種情況下它不起作用。 –

0

據微軟有關XML Declaration

XML聲明通常顯示爲一個XML 文檔中的第一行文檔。 XML聲明不是必需的,但是,如果使用它, 必須是文檔中的第一行,並且沒有其他內容或白色空間可以在其之前。

對於您的代碼,解析應該失敗,因爲空白先於XML聲明。刪除空格或xml聲明將導致成功解析。

換句話說,如果XmlReaderSettings與XML聲明的文檔不一致,那將是一個錯誤 - 它是定義的行爲。

下面是演示上述規則的一些代碼。

using System; 
using System.Web; 
using System.Xml; 
using System.Xml.Linq; 

public class Program 
{ 
    public static void Main() 
    { 
     //The XML declaration is not required, however, if used it must 
     // be the first line in the document and no other content or 
     //white space can precede it. 

     // here, no problem because this does not have an XML declaration 
      string xml = @"                
         <xml></xml>"; 
      XDocument doc = XDocument.Parse(xml); 
      Console.WriteLine(doc.Document.Declaration); 
      Console.WriteLine(doc.Document); 
     // 
     // problem here because this does have an XML declaration 
     // 
     xml = @"          
     <?xml version=""1.0"" encoding=""utf-8"" ?><xml></xml>"; 
     try 
     { 
     doc = XDocument.Parse(xml); 
      Console.WriteLine(doc.Document.Declaration); 
      Console.WriteLine(doc.Document); 
     } catch(Exception e) { 
      Console.WriteLine(e.Message); 
     } 

    } 
}