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

时间:2010-09-17 15:45:00

标签: c# linq-to-xml

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?

1 个答案:

答案 0 :(得分: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

完成