【发布时间】:2023-03-31 18:59:01
【问题描述】:
我有一个 WPF 应用程序,它调用 API 并使用 XDocument.Parse(string) 创建一个 System.Xml.Linq.XDocument。我遇到了一个问题,当我尝试执行此操作时会抛出 XmlException(“缺少根元素”),但我的 XML 完全有效。我尝试通过在浏览器中调用 API 并检查其语法、在我的应用程序中调用 API 并 Console.WriteLineing 响应以及使用各种 XML 语法验证器(所有这些都没有返回错误)来对其进行语法检查。
来自 API 的示例 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)));
}
为什么会这样?
【问题讨论】:
-
如果 xml 有效,它不会抛出该异常。你是如何进行“语法检查”的?
-
@Crowcoder 我仔细检查了格式以确保所有标签都关闭,所有引号都关闭,并且没有使用保留字符。我也用过W3School's XML Validator。
-
通常当“
标签: c# xml wpf linq-to-xml xmlexception