2009-08-01 44 views
2

假設我有以下XML文檔,如何獲取:name的元素值(在我的示例中,值是星期六100)?我的困惑是如何處理名稱空間。謝謝。問題,使用C#獲取特定的XML元素值。

我使用C#和VSTS 2008

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
    <s:Body> 
    <PollResponse xmlns="http://tempuri.org/"> 
     <PollResult xmlns:a="http://schemas.datacontract.org/2004/07/FOO.WCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
      <a:name>Saturday 100</a:name> 
     </PollResult> 
    </PollResponse> 
    </s:Body> 
</s:Envelope> 

回答

4

,如果你使用的LINQ to XML類很容易。否則命名空間真的很煩人。

XNamespace ns = "http://schemas.datacontract.org/2004/07/FOO.WCF"; 
var doc = XDocument.Load("C:\\test.xml"); 
Console.Write(doc.Descendants(ns + "name").First().Value); 

編輯。使用2.0

XmlDocument doc = new XmlDocument(); 
doc.Load("C:\\test.xml"); 
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); 
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF"); 
Console.Write(doc.SelectSingleNode("//a:name", ns).InnerText); 
+0

對不起我需要綁定到.Net 2.0。任何解決方案? – George2 2009-08-01 14:23:59

+0

非常感謝aquinas,您的解決方案有效! – George2 2009-08-02 09:26:12

5

使用System.Xml.XmlTextReader類,

System.Xml.XmlTextReader xr = new XmlTextReader(@"file.xml"); 
     while (xr.Read()) 
     { 
      if (xr.LocalName == "name" && xr.Prefix == "a") 
      { 
       xr.Read(); 
       Console.WriteLine(xr.Value); 
      } 
     } 
+0

感謝adatapost,我寧願使用XPATH,因爲它更加穩定和易於維護,假設我將來可能會更改XML請求和響應的格式。 – George2 2009-08-02 09:27:18

3

XPath是直接的方式來獲得在XML文檔中位2.0

XmlDocument xml = new XmlDocument(); 
xml.Load("file.xml") 
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable); 
manager.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF"); 
string name = xml.SelectSingleNode("//a:name", manager).InnerText;