raxinaga
raxinaga

Reputation: 421

convert xml string to json - remove xelement key

I using c# and I have xml string from database like this:

<ds>
  <table>
    <user>someuser1</user>
    <login>true</login>
  </table>
  <table>
    <user>someuser2</user>
    <login>true</login>
  </table>
</ds>

How can I convert this to JObject or JArray to this output?

[{ user: 'someuser1', login: 'true' }, { user: someuser2, login: 'false'} ]

I try to do that, but it is not what I expected.

var x = XElement.Parse(theXml).Elements("table");
var y = JsonConvert.SerializeObject(x);

it gets: [{ table: {user: ....} }, table: {....}]

Upvotes: 2

Views: 992

Answers (3)

Orell Buehler
Orell Buehler

Reputation: 116

This code gives you exactly your array:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(theXML);

string json = JsonConvert.SerializeXmlNode(xmlDocument);
JObject jObject = JObject.Parse(json);   

JArray jArray = (JArray) jObject.SelectToken("ds.table");

Upvotes: 0

Sam Sch
Sam Sch

Reputation: 672

My solution:

        var elements = XElement.Parse( xml ).Elements( "table" );
        var json = JsonConvert.SerializeObject( elements.Select( x => new
        {
            user = x.Element( "user" ).Value,
            login = x.Element( "login" ).Value
        } ) );

Upvotes: 4

Michał Turczyn
Michał Turczyn

Reputation: 37367

Try this code:

string xmlRaw = @"<ds>
                         <table>
                          <user>someuser1</user>
                          <login>true</login>
                         </table>
                         <table>
                          <user>someuser2</user>
                          <login>true</login>
                         </table>
                        </ds>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlRaw);
string json = JsonConvert.SerializeXmlNode(xml.SelectSingleNode("/ds"));
int startBracket = json.IndexOf('[');
int length = json.IndexOf(']', startBracket) - startBracket + 1;
json = json.Substring(startBracket, length);

Upvotes: 1

Related Questions