简体   繁体   中英

Extracting all key value pairs from “XML Like” text

I have a string

 value="test" 
 value3="343" 
_dff="323" 1212="2323". 

This is similar to a property declaration for XML string. I am trying to extract all property and value pairs.

 E.g value = test,
_dff = 323,

Probably value and field in two separate arrays?

In c#

You could do something like this:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<root " + yourString + "/>");

foreach(XmlAttribute att in doc.DocumentElement)
{
  // ... use att.Name & att.Value here
}

The drawback is it will not work if your string is not good xml. So you'll have to try if it really works for you. For example, "1212" is not a valid Xml attribute name...

Is there always 1 space between the property and value combination? If so you can split the string by ' ', then loop through the results and split each string by '='. Take the results of that and put them in whatever construct you think would be best (List of string[], Hashtable, KeyValuePair string/string would all work)

 string test = "test=1 test2=2 test3=3";
 List<string[]> values = new List<string[]>();

 string[] split1 = test.Split(' ');

 foreach (string s in split1)
 {
      string[] split2 = s.Split('=');
      values.Add(new string[]{split2[0],split2[1]});
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM