【问题标题】:How to read XML file without .xml format如何读取没有 .xml 格式的 XML 文件
【发布时间】:2013-10-17 06:43:43
【问题描述】:

所以我用 netbeans 创建了一个简单的 RESTful 服务,并在 localhost http://localhost:8080/testXML/webresources/entities.categoryid 中生成了一个 XML 文件

这个页面里面只有一个简单的xml文件格式:

<categoryids>
  <categoryid>
    <CategoryID>id1111</CategoryID>
    <CategoryName>Study</CategoryName>
  </categoryid>
</categoryids>

我正在使用 C# 读取 xml 文件,将它们放入数据集,最后放入 datagridview。我该怎么做呢?它使用

在本地(sample.xml)工作
ds.ReadXml(Application.StartupPath + "\\XML\\sample.xml", XmlReadMode.Auto);
dv = ds.Tables[0].DefaultView; 

但是它不适用于本地主机

ds.ReadXml("http://localhost:8080/testXML/webresources/entities.categoryid", XmlReadMode.Auto);

有没有办法做到这一点?

编辑:

NullRferenceException: Object reference not set to an instance of an object.

表示datagridview为空

edit2:抱歉,它应该是“ReadXml”而不是“WriteXml”

【问题讨论】:

  • 请永远不要告诉我们“它不起作用”。具体告诉我们,如何它不起作用。有例外吗?发布完整的例外!
  • NullReferenceException 的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
  • 你从哪里得到异常?我首先希望WriteXml 调用在ReadXml 调用之前失败...
  • @JonSkeet 很抱歉造成误解。它是 ReadXml,而不是 WriteXml
  • 那不是“误解”——那是“写一个完全虚假的问题”。你现在给ReadXml 打了两次电话——为什么?

标签: c# xml rest nullreferenceexception


【解决方案1】:

问题是您的 DataSet.ReadXml()-Method 无法从 URL 读取,因为您必须发送一个 GET-Request(参考http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml%28v=vs.80%29.aspx)。您需要发送一个 Web 请求来与您的 RESTful-Service 对话:

WebRequest request = WebRequest.Create ("http://localhost:8080/testXML/webresources/entities.categoryid");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream dataStream = response.GetResponseStream ();
ds.ReadXml(dataStream);
dataStream.Close();
response.Close();
...

我希望这对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2023-02-05
    相关资源
    最近更新 更多