不支持URI格式错误streamreader

时间:2016-01-31 08:38:18

标签: c# xml parsing url

我尝试从URL解析XML,我的代码是

public List<docs> parsexml(string url, string siteType)
    {
        var docsList = new List<docs>();
        using (var xmlReader = new StreamReader(url))
        {
            var doc = XDocument.Load(url);
            XNamespace nameSpace = "/response/result/";
            var xmlProducts = doc.Descendants(nameSpace + "docs");

我不知道在流阅读器旁边使用什么。 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

这应该有效:

Uri uri = new Uri("file:///c:/Test/file.xml");

WebResponse response = WebRequest.Create(uri).GetResponse();
using(Stream s = response.GetResponseStream()) {
    using (StreamReader sr = new StreamReader(s)) {
        var doc = XDocument.Load(sr);
        .........
    }
}

答案 1 :(得分:0)

您应该能够在最少的代码更改时使用WebClient;

public List<docs> parsexml(string url, string siteType)
{
    var docsList = new List<docs>();

    using (var client = new WebClient())
    using (var stream = client.OpenRead (url)) 
    {
        var doc = XDocument.Load(stream);
        XNamespace nameSpace = "/response/result/";
        var xmlProducts = doc.Descendants(nameSpace + "docs");
...

...或者,更好的是,您可以通过将URL传递给XDocument.Load();来简化它;

public List<docs> parsexml(string url, string siteType)
{
    var docsList = new List<docs>();

    var doc = XDocument.Load(url);
    XNamespace nameSpace = "/response/result/";
    var xmlProducts = doc.Descendants(nameSpace + "docs");

...