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