How to get specific value from a xml string in c#

bill picture bill · Apr 28, 2016 · Viewed 15.6k times · Source

I have following string

<SessionInfo>
  <SessionID>MSCB2B-UKT3517_f2823910df-5eff81-528aff-11e6f-0d2ed2408332</SessionID>
  <Profile>A</Profile>
  <Language>ENG</Language>
  <Version>1</Version>
</SessionInfo>

now I want to get the value of SessionID. I tried with below ..

var rootElement = XElement.Parse(output);//output means above string and this step has values

but in here,,

var one = rootElement.Elements("SessionInfo");

it didn't work.what can I do that.

and What if the xml string like below.can we use same to get the sessionID

<DtsAgencyLoginResponse xmlns="DTS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="DTS file:///R:/xsd/DtsAgencyLoginMessage_01.xsd">
  <SessionInfo>
    <SessionID>MSCB2B-UKT351ff7_f282391ff0-5e81-524548a-11eff6-0d321121e16a</SessionID>
    <Profile>A</Profile>
    <Language>ENG</Language>
    <Version>1</Version>
  </SessionInfo>
  <AdvisoryInfo />
</DtsAgencyLoginResponse>

Answer

har07 picture har07 · Apr 28, 2016

rootElement already references <SessionInfo> element. Try this way :

var rootElement = XElement.Parse(output);
var sessionId = rootElement.Element("SessionID").Value;