Web API返回XML,它看起来像这样(但有更多元素)。
<?xml version="1.0" encoding="UTF-8"?>
<root response="True">
<movie title="TRON" />
</root>
我有C#可以查询Web API,然后在控制台中显示XML。我需要能够只显示特定元素的值。对于此示例,我想显示“title”元素的值。
我有这个C#代码只返回一个空白的控制台窗口。
// Process the XML HTTP response
static public void ProcessResponse(XmlDocument MovieResponse)
{
//This shows the contents of the returned XML (MovieResponse) in the console window//
//Console.WriteLine(MovieResponse.InnerXml);
//Console.WriteLine();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(MovieResponse.NameTable);
XmlNode mTitle = MovieResponse.SelectSingleNode("/root/movie/title", nsmgr);
Console.WriteLine(mTitle);
Console.ReadLine();
}
答案 0 :(得分:0)
这些内容:
public List<string> GetMovieTitle(XDocument xdoc)
{
string xpath = @"//root/movie/title";
var query = xdoc.XPathSelectElements(xpath).Select(t => t.Value);
return query.ToList<string>();
}
可在此处找到更多选项:http://www.intertech.com/Blog/query-an-xml-document-using-linq-to-xml/
使用XmlDocument进行编辑:
static public void ProcessResponse(XmlDocument MovieResponse)
{
string xpath = @"//root/movie/@title";
var query = MovieResponse.SelectSingleNode(xpath).Value;
Console.WriteLine(query) ;
Console.ReadLine();
}