【问题标题】:XML from URL - Data at the root level is invalid. Line 1, position 1 Why it works with one URL and not the other?来自 URL 的 XML - 根级别的数据无效。第 1 行,位置 1 为什么它适用于一个 URL 而不是另一个?
【发布时间】:2020-06-21 07:15:14
【问题描述】:

据我所知,这两个端点都是有效的 XML 输出。但是,当我在第二个端点上使用相同的代码时,我得到了错误:

根级别的数据无效。第 1 行,位置 1

这是我的代码:

        //Works
        XmlDocument testDocument = new XmlDocument();
        testDocument.Load("https://www.w3schools.com/xml/note.xml");

        //Fails
        XmlDocument testDocumentTwo = new XmlDocument();
        testDocumentTwo.Load("https://www.domainNameHere.com/direct/umbraco/api/productsearch/NameSearch?countryCode=en-gb");

【问题讨论】:

    标签: c# xml xml-parsing xmldocument xmlreader


    【解决方案1】:

    我打开了 Fiddler 并查看了请求及其响应,你瞧你的端点返回的是 JSON,而不是 XML:

    如果我使用 HttpClient 设置显式的 Accept 标头,那么我会返回 XML 并且一切正常:

    using var client = new HttpClient();
    var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.clinigengroup.com/direct/umbraco/api/productsearch/NameSearch?countryCode=en-gb");
    requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
    var response = await client.SendAsync(requestMessage);
    var xml = await response.Content.ReadAsStringAsync();
    
    XmlDocument testDocumentTwo = new XmlDocument();
    testDocumentTwo.LoadXml(xml);
    

    【讨论】:

    • 它也不安全并且返回http(不是https)。
    • @jdweng 它正在为我返回 https...?
    • 真的吗?查看您发布的图片的第一行。
    • @jdweng HTTP/1.1?无论连接是否使用 TLS 保护,都会使用它
    • 我猜这取决于服务器。我经常看到https。
    猜你喜欢
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2020-12-19
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多