kalls
kalls

Reputation: 2855

Linq to XML - how to get the value of an element

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")

How to get the value UserID from the UserID element?

Upvotes: 0

Views: 130

Answers (1)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

Since the XML specifies xmlns='http://schemas.sample.com/sample.xsd' you will need to get the value by prefixing the namespace to the element:

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;

If the xmlns was not part of the XML you could have done it directly using config.Element("UserID").Value

Upvotes: 2

Related Questions