我使用c#,我有来自数据库的xml字符串,如下所示:
[{ user: 'someuser1', login: 'true' }, { user: someuser2, login: 'false'} ]
如何将此转换为JObject或JArray到此输出?
var x = XElement.Parse(theXml).Elements("table");
var y = JsonConvert.SerializeObject(x);
我尝试这样做,但这不是我的预期。
[{ table: {user: ....} }, table: {....}]
它得到:
fetchProfileData
答案 0 :(得分:4)
我的解决方案:
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
} ) );
答案 1 :(得分:1)
试试这段代码:
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);
答案 2 :(得分:0)
此代码为您提供了完整的数组:
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(theXML);
string json = JsonConvert.SerializeXmlNode(xmlDocument);
JObject jObject = JObject.Parse(json);
JArray jArray = (JArray) jObject.SelectToken("ds.table");