【问题标题】:read remote xml from server using c#使用c#从服务器读取远程xml
【发布时间】:2017-12-05 05:15:17
【问题描述】:

您好,我正在尝试从服务器获取简单的 xml 文件并读取数据,以便将其转换为列表。到目前为止,我尝试了一些库和代码,但没有成功。我在一行中获取 xml 内容,没有任何标签 并且计数始终为零。 XML 字符串。我需要获取营地标签内的数据

<campaigns>
 <mainPage>http://example.com</mainPage>
 <orderPage>https://www.example.co.il/adver/</orderPage>
 <totalCount>3</totalCount>
 <onLineCount>2</onLineCount>
  <campaignList>
   <camp id="557">
    <name>test1</name>
    <status>on</status>
    <rating>5</rating>
    <url>http://example.com/557</url>
  </camp>
  <camp id="559">
   <name>test1</name>
   <status>on</status>
   <rating>5</rating>
   <url>http://example.com/559</url>
 </camp>
 <camp id="660">
  <name>test1</name>
  <status>off</status>
  <rating>5</rating>
  <url>http://example.com/660</url>
 </camp>
</campaignList>

到目前为止我正在尝试的 c# 代码

XElement xelement = XElement.Load("http://example.com/test.xml");

    var name = from nm in xelement.Elements("camp")
               where (string)nm.Element("status") == "on"
               select nm;

    Response.Write(name.Count());

    foreach (XElement xEle in name)
    {
        Response.Write(xEle);
    }

【问题讨论】:

  • 如果您适当缩进它会更容易阅读 XML - 乍一看,它看起来像 campaignListonLineCount 的子元素。

标签: c# xml xelement


【解决方案1】:

XElement.Elements() 表示在子标签中搜索。我想你需要的是Descendants()xelement.Element("campaigns").Element("campaignList").Elements("camp")

【讨论】:

  • 感谢您的回复,我收到的 Object reference not set to an instance of an object message @Simon
  • 我看起来你没有得到任何数据。可能您需要使用凭据或代理来获取数据。因此,使用 webclient 而不是使用 XElement Load 将是解决方案。在得出任何结论之前,我建议尝试两件事 1) 将 url 放入 IE 并查看结果 2 ) 使用嗅探器获取实际错误。Net 不太擅长从连接中获取低级错误您是如何获取发布的 xml 文件的?我会使用嗅探器获取良好 xml 的结果并与您的应用程序进行比较,并使应用程序看起来不错。通常使用 webclient 您需要添加 html 标头
  • @jdweng 我出于隐私原因更改了网址。原始网址运行良好,数据存在
  • 在这里去掉Element("campaigns") - 根元素 campaigns(并且OP加载为XElement而不是XDocument)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多