私はAPIを呼び出すWPFアプリケーションがあり、XDocument.Parse(string)
を使用してSystem.Xml.Linq.XDocument
を作成しています。私はこれをやろうとするとXmlException
( "ルート要素が見つからない")という問題が発生していますが、XMLは完全に有効です。ブラウザでAPIを呼び出し、構文をチェックし、アプリケーションでAPIを呼び出し、応答を受け取って、さまざまなXML構文バリデーター(すべてエラーを返さなかった)を使用して構文チェックを試みました。
APIからのサンプルXML応答は次のとおりです。有効なXMLを解析するときのXmlException
<?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)));
}
ですが、なぜでしょうか? XMLは、それがその例外をスローしないと有効であった場合
に動作します。どのように "構文チェック"をやっていますか? – Crowcoder
@Crowcoderすべてのタグが閉じられ、すべての引用符が閉じられ、予約文字が使用されていないことを確認するために、フォーマットを注意深くチェックします。私は[W3SchoolのXML Validator](http://www.w3schools.com/xml/xml_validator.asp)も使用しました。 –
通常、このエラーは "<?xml"がデータの最初の文字でない場合に発生します。通常、最初のスペースまたは余分な文字がこのエラーの原因になります。 – jdweng