Search code examples
c#xmlxelement

read remote xml from server using c#


Hello i am trying to get simple xml file from server and to read the data so i can convert it to list. I was try few lib and code with no success so far. I am getting the xml content in one line without any tags <> and the count is always 0 zero. The XML string. I need to get the data that inside camp tag

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

And the c# code i am trying so far

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

Solution

  • XElement.Elements() means search in children tags. I think what you need is Descendants() or xelement.Element("campaigns").Element("campaignList").Elements("camp")