Home > Software engineering >  Extract certain parts from XML string
Extract certain parts from XML string

Time:06-21

I have a windows form in C# that does a httpclient get request. And this is the response in XML format

>  <Result><Success>true</Success><Token>MYTOKENHERE</Token><TokenExpirationDate null="1"
> /><UserName>********</UserName><PersonCode>442078</PersonCode><LoginStatusMessage>LoginOk</LoginStatusMessage></Result>

I want to set the text of a text box to what is inbetween the <Token></Token> Tags

What is the best approach to do this

Thanks

This is my current Form1.cs code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Xml.Serialization;

namespace EBS_Token_Form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

     

        private void button1_Click(object sender, EventArgs e)
        {
            HttpClient Client = new HttpClient();
            Client.BaseAddress = new Uri("PRIVATE_URL");

            string Username = username.Text;
            string Password = password.Text;



            string CredentialsString = $"{Username}:{Password}";
            byte[] CredentialsStringByes = System.Text.Encoding.UTF8.GetBytes(CredentialsString);

            Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("basic", Convert.ToBase64String(CredentialsStringByes));

            try
            {
                var Response = Client.GetAsync("Rest/Authentication").Result;

                if (!Response.IsSuccessStatusCode)
                {
                    // Something went wrong, is error.
                    // Put a breakpoint on the line below and we can figure out why.
                    string x = "";
                }

                string ServerResponse = Response.Content.ReadAsStringAsync().Result;

              
            }

            catch (Exception ex)
            {
                return;
            }


        } 

If i set the value of the textbox to ServerResponse it has the full xml document. I need to extract just the .

CodePudding user response:

Usually I'd use XmlSerializer for something like this, but if you really just need this one value, you may want to try XElement:

var root = XElement.Parse(yourResponseString);
var value = root.Element("Token")?.Value;

XElement is great for traversing, reading and manipulating XML.

CodePudding user response:

XPath works for this, although some might consider overkill. The XPath expression /Result/Token/Text() does exactly what it looks like it will.

using System.Xml;
using System.Xml.XPath;

string Incoming_XML = @"<Result><Success>true</Success><Token>MYTOKENHERE</Token><TokenExpirationDate null=""1"" /><UserName>********</UserName><PersonCode>442078</PersonCode><LoginStatusMessage>LoginOk</LoginStatusMessage></Result>";

XPathDocument xPathDoc = null;

using (StringReader sr = new StringReader(Incoming_XML))
{
    xPathDoc = new XPathDocument(sr);
    XPathNavigator xPathNav = xPathDoc.CreateNavigator();
    string Result = xPathNav.SelectSingleNode("/Result/Token/text()").Value;
    Console.WriteLine($"Token is: {Result}");
}

CodePudding user response:

below sample code may not the best but it is simple to understand and will do the work.

        // Define a regular expression pattern 
        string Regex_syntax = @"<Token>[\s\S]*?</Token>";

        
        Regex rx = new Regex(Regex_syntax,RegexOptions.Compiled | RegexOptions.IgnoreCase);


        // Define a RAW data string to process , in your case will be http response result
        string inputtext = @"<Result><Success>true</Success><Token>MYTOKENHERE</Token><TokenExpirationDate";


        // Find matches.
        MatchCollection matches = rx.Matches(inputtext);

        // clease the uneeded string 
        string cleanseString = matches[0].ToString().Replace(@"<Token>", "");
        cleanseString = cleanseString.Replace(@"</Token>", "");

        // This will print value in between the token tag
        Console.WriteLine("require output = "   cleanseString);
  • Related