How to retrieve data from XML between tags using c#?

Deadly 提交于 2020-01-16 16:48:40

问题


I'm making an HTTP call to a webservice which gives me a response in an XML format. The problem that i'm facing right now is on how to read those data which are in between the elements.

Below is my code.

        XmlDocument document = new XmlDocument();

        document.Load("http://thecatapi.com/api/categories/list");

        XmlNodeList categoryNodes = document.SelectNodes("//response/data/categories");

        foreach (XmlNode categoryNode in categoryNodes)
        {
            XmlNode category = categoryNode.SelectSingleNode("category");
           var id =categoryNode.Attributes["id"].InnerXml;
           string name = categoryNode.Attributes["name"].InnerText;
        }
        document.Save("test-doc.xml");

Here is the structure of the XML

      <response>
          <data>
             <categories>
                  <category>
                      <id>5</id>
                      <name>boxes</name>
                  </category>
                  <category>
                      <id>8</id>
                      <name>boys</name>
                  </category>
              </categories>
           </data>
       </response>

回答1:


try using XElement

try
{
    XElement booksFromFile = XElement.Load("http://thecatapi.com/api/categories/list");

    var category = booksFromFile.Element("data").Element("categories").Elements("category");

    foreach (var element in category)
    {
        var id = element.Element("id").Value;
        var name = element.Element("name").Value; 
    }
    booksFromFile.Save("test-doc.xml");
}
catch (Exception e)
{
    //handle and log the error here
}


来源:https://stackoverflow.com/questions/57241011/how-to-retrieve-data-from-xml-between-tags-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!