Home > Net >  Trying to convert XML to JSON with = and & characters
Trying to convert XML to JSON with = and & characters

Time:08-09

I have the following XML string,

<xml><row ID="61" url="Page.aspx?stepid=MyStepID&ID=65454&UserID=2542240&process=MyProcess"></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 = and all the keys are separated by the character &.

How should I convert this string to JSON?

CodePudding user response:

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?stepid=MyStepID&ID=65454&UserID=2542240&process=MyProcess\"></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?stepid=MyStepID&ID=65454&UserID=2542240&process=MyProcess\"></row></xml>";

CodePudding user response:

try this

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(xml);
    XmlNode node = xmlDoc.SelectSingleNode("xml");


    var rawjson = JsonConvert.SerializeXmlNode(node); 
    var jsonParsed = JObject.Parse(rawjson);
    jsonParsed["xml"]["row"]["@url"] = HttpUtility.UrlDecode((string) jsonParsed["xml"]["row"]["@url"]);
    
    var json=jsonParsed["xml"].ToString();

json

{
  "row": {
    "@ID": "61",
    "@url": "Page.aspx?stepid=MyStepID&ID=65454&UserID=2542240&process=MyProcess"
  }
}
  • Related