2012-06-01 58 views
4

我有一個XElement,它有這樣的內容。如何從LINQ到XML中的XElement中讀取特定元素值

<Response xmlns="someurl" xmlnsLi="thew3url"> 
    <ErrorCode></ErrorCode> 
    <Status>Success</Status> 
    <Result> 
     <Manufacturer> 
      <ManufacturerID>46</ManufacturerID> 
      <ManufacturerName>APPLE</ManufacturerName> 
     </Manufacturer> 
     //More Manufacturer Elements like above here 
    </Result> 
</Response> 

我將如何讀Status元素中的價值?

我試過XElement stats = myXel.Descendants("Status").SingleOrDefault();但是,返回null。

回答

2
XElement response = XElement.Load("file.xml"); // XElement.Parse(stringWithXmlGoesHere) 
XNamespace df = response.Name.Namespace; 
XElement status = response.Element(df + "Status"); 

應該足以訪問Status子元素。 如果你想把那個元素的值作爲一個字符串,

string status = (string)response.Element(df + "Status"); 
2

如果myXel已經是響應XElement那麼這將是:

var status = myXel.Elements().Where(e => e.Name.LocalName == "Status").Single().Value; 

您需要使用的localName忽略的命名空間。