2016-07-23 47 views
0

XML正在由Web API返回,它看起來像這樣(但包含更多元素)。如何使用C#獲取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

東西沿着這些路線:

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(); 
} 
+0

我希望只修改ProcessResponse類我已經有了。 –

+0

這是做這種情況的伎倆!非常感謝你!現在我可以更深入地瞭解如何獲取元素值。謝謝! –

+0

@MrXeon你是最受歡迎的 – objectNotFound