How to get specific value from a xml string in c#
19,608
Solution 1
rootElement
already references <SessionInfo>
element. Try this way :
var rootElement = XElement.Parse(output);
var sessionId = rootElement.Element("SessionID").Value;
Solution 2
You can select node by xpath and then get value:
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<SessionInfo>
<SessionID>MSCB2B-UKT3517_f2823910df-5eff81-528aff-11e6f-0d2ed2408332</SessionID>
<Profile>A</Profile>
<Language>ENG</Language>
<Version>1</Version>
</SessionInfo>");
string xpath = "SessionInfo/SessionID";
XmlNode node = doc.SelectSingleNode(xpath);
var value = node.InnerText;
Author by
bill
Updated on June 08, 2022Comments
-
bill almost 2 years
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>
-
MakePeaceGreatAgain about 8 yearsThe
XElement
IS ".NET-Stuff" and comes with LinqToXml. It´s absoutely okay to do it like this. -
Nick Mertin about 8 yearsThe call to
String.Format
is completely unnecessary here -
MakePeaceGreatAgain about 8 yearsI guess OP is only interested in a single value, thus he won´t need this overhead of creating the classes and adding the serializer-attributes. The approach of har07 works smart and is absouteley fine for this purpose.
-
har07 about 8 years@bill I agree with HimBromBeere. Anyway, the keyword is default namespace. The 2nd XML has default namespace
xmlns="DTS"
. Try to search for how to select element in namespace using LINQ-to-XML...