Pregunta

I have following string:

OK:<IDP RESULT="0" MESSAGE="some message" ID="oaisjd98asdh339wnf" MSGTYPE="Done"/>

I use this method to parse and get result:

public string MethodName(string capt)
{
    var receivedData = capt.Split(' ').ToArray();
    string _receivedReultValue = "";
    foreach (string s in receivedData)
    {
        if (s.Contains('='))
        {
            string[] res = s.Split('=').ToArray();
            if (res[0].ToUpper() == "RESULT")
            {
                string resValue = res[1];
                resValue = resValue.Replace("\\", " ");
                _receivedReultValue = resValue.Replace("\"", " ");
            }
        }
    }

    return _receivedReultValue.Trim();
}

Is there better way to parse string like this to extract data?

¿Fue útil?

Solución

What you have isn't all that bad. But, because it's XML you could do this:

class Program
{
    static void Main(string[] args)
    {
        var capt = "OK:<IDP RESULT=\"0\" MESSAGE=\"some message\" ID=\"oaisjd98asdh339wnf\" MSGTYPE=\"Done\"/>";
        var stream = new MemoryStream(Encoding.Default.GetBytes(capt.Substring(capt.IndexOf("<"))));
        var kvpList = XDocument.Load(XmlReader.Create(stream))
                   .Elements().First()
                   .Attributes()
                   .Select(a => new
                   {
                       Attr = a.Name.LocalName,
                       Val = a.Value
                   });
    }
}

That would give you an IEnumerable of that anonymous type.

Otros consejos

You can use XDocument, assuming that you will remove the "OK:" at the beginning you can do it like this:

    static void Main(string[] args)
    {
        var str = "<IDP RESULT=\"0\" MESSAGE=\"some message\" ID=\"oaisjd98asdh339wnf\" MSGTYPE=\"Done\"/>";
        var doc = XDocument.Parse(str);
        var element = doc.Element("IDP");
        Console.WriteLine("RESULT: {0}", element.Attribute("RESULT").Value);
        Console.WriteLine("MESSAGE: {0}", element.Attribute("MESSAGE").Value);
        Console.WriteLine("ID: {0}", element.Attribute("ID").Value);
        Console.WriteLine("MSGTYPE: {0}", element.Attribute("MSGTYPE").Value);

        Console.ReadKey();
    }

EDIT: I tested the code above on .NET 4.5. For 3.5 I had to change it a bit

    static void Main(string[] args)
    {
        const string str = "<IDP RESULT=\"0\" MESSAGE=\"some message\" ID=\"oaisjd98asdh339wnf\" MSGTYPE=\"Done\"/>";
        var ms = new MemoryStream(Encoding.ASCII.GetBytes(str));
        var rdr = new XmlTextReader(ms);
        var doc = XDocument.Load(rdr);
        var element = doc.Element("IDP");
        Console.WriteLine("RESULT: {0}", element.Attribute("RESULT").Value);
        Console.WriteLine("MESSAGE: {0}", element.Attribute("MESSAGE").Value);
        Console.WriteLine("ID: {0}", element.Attribute("ID").Value);
        Console.WriteLine("MSGTYPE: {0}", element.Attribute("MSGTYPE").Value);

        Console.ReadKey();
    }

Sure. It looks like XML, you may use normal XML methods for this. if you remove "OK" and add

<?xml version="1.0" ?>
<IDP RESULT="0" MESSAGE="some message" ID="oaisjd98asdh339wnf" MSGTYPE="Done"/>

this can be parsed by any XML decoder. Try xmllint to check it out.

You can Regex to obtain all key/value pairs:

string str = @"OK:<IDP RESULT=""0"" MESSAGE=""some message"" ID=""oaisjd98asdh339wnf"" MSGTYPE=""Done""/>";
var matches = Regex.Matches(str, @"(?<Key>\w+)=""(?<Value>[^""]+)""");

then you can access RESULT attribute:

var match = matches.OfType<Match>()
                   .FirstOrDefault(match => match.Groups["Key"].Value == "RESULT");
if (match != null)
{
    result = match.Groups["Value"].Value;
}

try this is too simple

 string xml = @"OK:<IDP RESULT=""0"" MESSAGE=""some message"" ID=""oaisjd98asdh339wnf"" MSGTYPE=""Done""/>";


        XElement xElement = XElement.Parse(new string(xml.Skip(3).ToArray()));
        //for example message 
          var message  = xElement.Attribute("MESSAGE").Value;  
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top