2016-05-30 80 views
0

我有一個WPF應用程序調用API並使用XDocument.Parse(string)創建System.Xml.Linq.XDocument。我遇到了一個問題,我試圖這樣做時拋出了XmlException(「根元素丟失」),但是我的XML完全有效。我嘗試通過在瀏覽器中調用API並檢查其語法,在我的應用程序中調用API以及使用各種XML語法驗證程序(所有這些驗證程序都不返回錯誤)來嘗試進行語法檢查。
從API的示例XML響應如下:XmlException解析XML時有效

<?xml version="1.0" encoding="UTF-8"?> 
<response> 
    <event title="Event 1" id="75823347" icon="www.example.com/images/event1-icon.png" uri="www.example.com/rsvp/event1" mode="none" price="10.00" cover="www.example.com/event1-cover.png" enddate="2016-06-01 14:00:00" startdate="2016-06-01 12:00:00" address="1 Example St, Example City State 12345" location="Example Place" description="This is an event" shortdescription="This is an event" theme="auto" color="#FF000000"/> 
</response> 

這是我的應用程序的代碼:

public static WebRequest CreateRequest(string baseUrl, string httpMethod, Dictionary<string, string> requestValues) { 
    var requestItems = requestValues == null ? null : requestValues.Select(pair => string.Format("&{0}={1}", pair.Key, pair.Value)); 
    var requestString = ""; 
    if (requestItems != null) 
     foreach (var s in requestItems) 
      requestString += s; 
    var request = WebRequest.CreateHttp(baseUrl + CredentialRequestString + requestString); 
    request.Method = httpMethod.ToUpper(); 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.Credentials = CredentialCache.DefaultCredentials; 
    return request; 
} 

public static WebRequest CreateRequest(string apiEndpoint, string endpointParam, int apiVersion, string httpMethod, Dictionary<string, string> requestValues) { 
    return CreateRequest(string.Format("http://www.example.com/api/v{0}/{1}/{2}", apiVersion, apiEndpoint, endpointParam), httpMethod, requestValues); 
} 

public static async Task<string> GetResponseFromServer(WebRequest request) { 
    string s; 
    using (var response = await request.GetResponseAsync()) { 
     using (var responseStream = response.GetResponseStream()) { 
      using (var streamReader = new StreamReader(responseStream)) { 
       s = streamReader.ReadToEnd(); 
      } 
     } 
    } 
    return s; 
} 

public static async Task<List<Event>> GetEvents() { 
    var response = await GetResponseFromServer(CreateRequest("events", "", 1, "GET", null)); 
    Console.WriteLine(response); //validation 
    var data = XDocument.Parse(response).Root; //XmlException: Root element is mising 
    return new List<Event>(data.Elements("event").Select(e => Event.FromXml(e.Value))); 
} 

這究竟是爲什麼?

+0

如果XML是有效的它不會拋出該異常。你如何做「語法檢查」? – Crowcoder

+0

@Crowcoder我仔細檢查格式以確保所有標籤都關閉,所有引號都關閉,並且沒有使用保留字符。我還使用了[W3School的XML驗證器](http://www.w3schools.com/xml/xml_validator.asp)。 –

+0

當「<?xml」不是數據中的第一個字符時,通常會發生此錯誤。通常在開頭的空格或額外的字符將導致此錯誤。 – jdweng

回答

1

下面的代碼工作

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      var data = XDocument.Load(FILENAME); 
      Event _event = Event.FromXml(data.Descendants("event").FirstOrDefault()); 
     } 
    } 
    public class Event 
    { 
     public string title { get ; set; } 
     public string icon {get; set; } 
     public string uri { get; set; } 
     public string mode { get;set; } 
     public decimal price { get; set; } 
     public string cover { get; set; } 
     public DateTime enddate { get; set; } 
     public DateTime startdate { get; set; } 
     public string address { get; set; } 
     public string location { get; set; } 
     public string description { get; set; } 
     public string shortdescription { get; set; } 
     public string theme { get; set; } 
     public uint color { get; set; } 


     public static Event FromXml(XElement data) 
     { 
      Event _event = new Event(); 

      _event.title = (string)data.Attribute("title"); 
      _event.icon = (string)data.Attribute("icon"); 
      _event.uri = (string)data.Attribute("uri"); 
      _event.mode = (string)data.Attribute("mode"); 
      _event.price = (decimal)data.Attribute("price"); 
      _event.cover = (string)data.Attribute("cover"); 
      _event.enddate = (DateTime)data.Attribute("enddate"); 
      _event.startdate = (DateTime)data.Attribute("startdate"); 
      _event.address = (string)data.Attribute("address"); 
      _event.location = (string)data.Attribute("location"); 
      _event.description = (string)data.Attribute("description"); 
      _event.shortdescription = (string)data.Attribute("shortdescription"); 
      _event.theme = (string)data.Attribute("theme"); 
      _event.color = uint.Parse(data.Attribute("color").Value.Substring(1), System.Globalization.NumberStyles.HexNumber) ; 

      return _event; 
     } 

    } 
} 
+0

我接受這個解決方案,因爲我自己實現'FromXml'對我來說非常奇怪,有點愚蠢。我重寫它的工作類似於你的,現在一切工作正常。 –

+0

您的第一個錯誤是由於在您的linq查詢中使用了'Root',它從xml中刪除了標識行。我很快注意到這個錯誤,但是你的xml linq查詢看起來不正確,所以我決定解決這兩個問題。 – jdweng