tags:

views:

38

answers:

1
XElement config = XElement.Parse(
@"<Response SessionId='BEDF38F9ADAB4F029404C69E49951E73' xmlns='http://schemas.sample.com/sample.xsd'&gt;
    <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?

+2  A: 

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'&gt;
    <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

Ahmad Mageed
+1. I didn't bother to scroll over, so I missed the `xmlns`.
Adam Robinson
also can use just (string)config.Element("UserID")
Leo Nowaczyk
Thanks! It works great.
Kalls
@Adam it happens :) @Leo yes that's possible too. I prefer `Value` when I know the XML will contain the element, otherwise casting with `(string)` is great when the element may not be there, in which case `null` is returned. Using `Value` when the element is missing would throw a `NullReferenceException`. Thus casting has a 2-in-1 benefit but `Value` helps with readability and intention IMO. I thought I would clarify for the benefit of future readers wondering what the differences were.
Ahmad Mageed