2010-09-17 83 views
0
XElement config = XElement.Parse(
@"<Response SessionId='BEDF38F9ADAB4F029404C69E49951E73' xmlns='http://schemas.sample.com/sample.xsd'> 
    <Status Success='true' Message='User is now logged in.' ErrorCode='0' /> 
    <UserID>80077702-0</UserID> 
    </Response>");  
string masterID = (string)config.Element("UserID") 

如何从UserID元素获取值UserID?Linq to XML - 如何获取元素的值

回答

2

由于XML指定xmlns='http://schemas.sample.com/sample.xsd'您将需要前缀命名空间的元素来获取值:

XElement config = XElement.Parse(@"<Response SessionId='BEDF38F9ADAB4F029404C69E49951E73' xmlns='http://schemas.sample.com/sample.xsd'> 
    <Status Success='true' Message='User is now logged in.' ErrorCode='0' /> 
    <UserID>80077702-0</UserID> 
    </Response>");  

var ns = config.GetDefaultNamespace(); 
string masterID = config.Element(ns + "UserID").Value; 

如果xmlns不是你可以做它的XML的部分,直接使用config.Element("UserID").Value

+0

+1。我懒得翻看,所以我错过了'xmlns'。 – 2010-09-17 15:59:14

+0

也可以使用just(string)config.Element(“UserID”) – 2010-09-17 15:59:52

+0

谢谢!它效果很好。 – kalls 2010-09-17 16:01:03