Reputation: 3678
I have the following XML string,
<xml><row ID="61" url="Page.aspx%3fstepid%3dMyStepID%26ID%3d65454%26UserID%3d2542240%26process%3dMyProcess"></row></xml>
I need to convert only the attributes from the URL part of the string to the JSON model.
For example,
StepID:MyStepID
ID:65454
UserID:2542240
Process:MyProcess
I see that the key and value in the string are separated by %3D
and all the keys are separated by the character %26
.
How should I convert this string to JSON?
Upvotes: 0
Views: 282
Reputation: 43931
try to use HttpUtility.UrlDecode to decode query string
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var url= xmlDoc.DocumentElement.GetElementsByTagName("row")[0].Attributes["url"].Value;
var queryString = HttpUtility.UrlDecode(url);
var index=queryString.IndexOf(".aspx?");
index=index>0?index+6:0;
queryString = queryString.Substring(index);
var pairs = HttpUtility.ParseQueryString(queryString);
var parameters = (from key in pairs.Cast<string>()
from value in pairs.GetValues(key)
select ( key,value)).ToDictionary(p => p.key, p=> p.value);
var json = JsonConvert.SerializeObject(parameters, Newtonsoft.Json.Formatting.Indented);
json
{
"stepid": "MyStepID",
"ID": "65454",
"UserID": "2542240",
"process": "MyProcess"
}
Upvotes: 1
Reputation: 23807
You can UrlDecode it and get query parameters. ie:
void Main()
{
var urlString = (string)XElement
.Parse(myxml)
.Element("row")
.Attribute("url");
var query = new Uri("http://myurl/"+HttpUtility.UrlDecode(urlString)).Query;
var parameters = HttpUtility.ParseQueryString(query);
foreach (var key in parameters.AllKeys)
{
Console.WriteLine($"Key:{key}, Value:{parameters[key]}");
}
}
static readonly string myxml = "<xml><row ID=\"61\" url=\"Page.aspx%3fstepid%3dMyStepID%26ID%3d65454%26UserID%3d2542240%26process%3dMyProcess\"></row></xml>";
Output:
Key:stepid, Value:MyStepID
Key:ID, Value:65454
Key:UserID, Value:2542240
Key:process, Value:MyProcess
EDIT: I missed that you want to convert that to JSON. Then you could use Newtonsoft from Nuget:
void Main()
{
var urlString = (string)XElement
.Parse(myxml)
.Element("row")
.Attribute("url");
var query = new Uri("http://myurl/"+HttpUtility.UrlDecode(urlString)).Query;
var parameters = HttpUtility.ParseQueryString(query);
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (var key in parameters.AllKeys)
{
Console.WriteLine($"Key:{key}, Value:{parameters[key]}");
dic.Add(key, parameters[key]);
}
var json = JsonConvert.SerializeObject(dic);
}
static readonly string myxml = "<xml><row ID=\"61\" url=\"Page.aspx%3fstepid%3dMyStepID%26ID%3d65454%26UserID%3d2542240%26process%3dMyProcess\"></row></xml>";
Upvotes: 2