-->

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

2019-07-05 15:09发布

问题:

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>

回答1:

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

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


回答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;


回答3:

Please do not do this manually. This is horrible. Use .NET built in stuff to make it simpler and more reliable

XML Serialisation

This is the right way to do it. You create Classes and let them be serialized automatically from an XML string.



回答4:

Try this method :

   private string parseResponseByXML(string xml)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);
        XmlNodeList xnList = xmlDoc.SelectNodes("/SessionInfo");
        string node ="";
        if (xnList != null && xnList.Count > 0)
        {
            foreach (XmlNode xn in xnList)
            {
                node= xn["SessionID"].InnerText;

            }
        }
        return node;
    }

Your nodes :

xmlDoc.SelectNodes("/SessionInfo");

Different sample

 xmlDoc.SelectNodes("/SessionInfo/node/node");

I hope it helps.