Parsing XML response

2020-08-03 09:17发布

问题:

I got an XML response as:

 <Resp>
<status>00</status>
<errorcode></errorcode>
<errordescr></errordescr>
<data>
    <Table>
        <USERNAME>Name</USERNAME>
        <ACCLOCK>N</ACCLOCK>
        <EMAILID>Samplemail@gmail.com</EMAILID>
        <LASTLOGINDATE>23-03-2015 12:35:40</LASTLOGINDATE>
        <LOGINSTATUS>N</LOGINSTATUS>
        <MOBILENO>9848022338</MOBILENO>
        <PASSWORD>Abcd@1234</PASSWORD>
        <PWDCOUNT>0</PWDCOUNT>
        <PWDVALIDTO>12-05-2015 12:18:10</PWDVALIDTO>
        <DESCRIPTION>Shop Person</DESCRIPTION>
        <STATUS>Y</STATUS>
        <USRID_FK>100017</USRID_FK>
        <ROLE>12</ROLE>
        <COUNTRY>61</COUNTRY>
        <MERID_FK>100002</MERID_FK>
        <GENDER>0</GENDER>
        <COUNTRY1>61</COUNTRY1>
        <STATE>0</STATE>
        <DOB>12-02-1997</DOB>
        <STRID_FK>10025</STRID_FK>
    </Table>
</data>

I am saving this XML response in the following string:

string response;

I want to split the string response and get values of some tags (EX:-USERNAME, STRID_FK, MERID_FK), to save it in other strings for further usage.

Please help me with this ..

回答1:

Another option, this time using Linq to Xml:

var yourXml = XElement.Parse (response); // Parse the response

// Look up specific values by name:
var username = yourXml.Descendants().First(node => node.Name == "USERNAME").Value;

Yet another option is to put all the data from <Table>...</Table> into a dictionary for easy lookup later:

var dict = yourXml.Descendants()
                  .Where(node => node.Name == "Table")
                  .Descendants()
                  .ToDictionary(node => node.Name.ToString(), node => node.Value);

// Look up value using "USERNAME" as key:
var exampleUsername = dict["USERNAME"];


回答2:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString);

XmlNodeList xnList = xml.SelectNodes("/data/Table");
foreach (XmlNode xn in xnList)
{
  string USERNAME= xn["USERNAME"].InnerText;
  string STRID_FK= xn["STRID_FK"].InnerText;
  string MERID_FK= xn["MERID_FK"].InnerText;
  Console.WriteLine("Name: {0, {1}, {2}", USERNAME, STRID_FK,MERID_FK);
}

or if try directly to select node xmlDoc.SelectNodes("/data/Table/USERNAME") or

XmlNodeList nodes= doc.GetElementsByTagName("USERNAME");