简体   繁体   English

XmlException解析有效的XML时

[英]XmlException When Parsing Valid XML

I have a WPF application that calls an API and creates an System.Xml.Linq.XDocument using XDocument.Parse(string) . 我有一个WPF应用程序,该应用程序调用API并使用XDocument.Parse(string)创建System.Xml.Linq.XDocument I am running into a problem where an XmlException ("Root element is missing") is thrown when I try to do this, but my XML is completely valid. 我遇到一个问题,当我尝试执行此操作时会抛出XmlException (“根元素丢失”),但是我的XML是完全有效的。 I tried syntax-checking it by calling the API in my browser and checking its syntax, calling the API in my application and Console.WriteLine ing the response, and using various XML syntax validators (all of which returned no errors). 我尝试通过在浏览器中调用API并检查其语法,然后在应用程序和Console.WriteLine调用API来对响应进行语法检查,并使用各种XML语法验证器(所有语法均未返回错误)。
A sample XML response from the API is as follows: 该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>

This is my application's code: 这是我的应用程序的代码:

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)));
}

Why is this happening? 为什么会这样呢?

The following code works 以下代码有效

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;
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在有效的XML上获得XmlException? - Why am I getting an XmlException on valid XML? 解析XML导致System.Xml.XmlException:找不到元素&#39;Customer&#39; - Parsing XML leads to System.Xml.XmlException: Element 'Customer' was not found 加载带有某些字符的XML文件时出现XmlException - XmlException when loading an XML file with certain characters 解析xml时的XmlException,编码指定为“utf-16” - XmlException while parsing xml with encoding specified as “utf-16” 使用C#和XDocument进行XML解析-XmlException:预期为“文件” - XML Parsing with C# and XDocument - XmlException: 'file' is expected 将XML字符串作为值添加到XML SOAP请求正文中时的XmlException - XmlException when adding an XML string as a value in an XML SOAP request body System.Xml.XmlException:根级别的数据无效。 第 1 行,position 1 - 有效的 XML 文件? - System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1 - Valid XML file? System.Xml.XmlException:解析名称时发生了意外的文件结尾 - System.Xml.XmlException: Unexpected end of file while parsing Name has occurred 处理RSS时出现XMLException - XMLException when processing RSS System.Xml.XmlException: 给定编码中的字符无效。 第 1 行,位置 1。使用 Nuget 时 - System.Xml.XmlException: Invalid character in the given encoding. Line 1, position 1. When using Nuget
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM