<?xml version="1.0"?>
<Message>
<Row>
<SceneId>2</SceneId>
<Name>无天气预报</Name>
<Description />
</Row>
<Row>
<SceneId>1</SceneId>
<Name>有天气预报</Name>
<Description />
</Row>
</Message>
=============================
因为root和集合冲突,直接定义Message类和Row类好像是不行的
https://jsonformatter.org/xml-to-csharp
// <auto-generated /> // // To parse this JSON data, add NuGet 'Newtonsoft.Json' then do: // // using CodeBeautify; // // var welcome2 = Welcome2.FromJson(jsonString); namespace CodeBeautify { using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; public partial class Welcome2 { [JsonProperty("Message")] public Message Message { get; set; } } public partial class Message { [JsonProperty("Row")] public Row[] Row { get; set; } } public partial class Row { [JsonProperty("SceneId")] [JsonConverter(typeof(ParseStringConverter))] public long SceneId { get; set; } [JsonProperty("Name")] public string Name { get; set; } [JsonProperty("Description")] public string Description { get; set; } } public partial class Welcome2 { public static Welcome2 FromJson(string json) => JsonConvert.DeserializeObject<Welcome2>(json, CodeBeautify.Converter.Settings); } public static class Serialize { public static string ToJson(this Welcome2 self) => JsonConvert.SerializeObject(self, CodeBeautify.Converter.Settings); } internal static class Converter { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, DateParseHandling = DateParseHandling.None, Converters = { new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } }, }; } internal class ParseStringConverter : JsonConverter { public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?); public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; var value = serializer.Deserialize<string>(reader); long l; if (Int64.TryParse(value, out l)) { return l; } throw new Exception("Cannot unmarshal type long"); } public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer) { if (untypedValue == null) { serializer.Serialize(writer, null); return; } var value = (long)untypedValue; serializer.Serialize(writer, value.ToString()); return; } public static readonly ParseStringConverter Singleton = new ParseStringConverter(); } }
不需要人去干,有的是工具。
感谢啊,幸福来得太突然,差点整懵了
看了半天,才反应过来
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsontext = JsonConvert.SerializeXmlNode(doc);
var welcome2 = CodeBeautify.Welcome2.FromJson(jsontext);
这个工具唯一的不足是需要科学上网