JsonConvert.SerializeXNode("<Root><Student key="Student1" value="4" /> <Student key="Student2" value="0" /></Root>")
它的回归
{"Root":{Student:[{key:Student1,value=4}},Student:{key:Student2,value=0}]}
但我需要
JsonConvert.SerializeXNode("<Root><Student key="Student1" value="4" /></Root>")
来自
{"Root":[{Student:{key:Student1,value=4}}]}
但它回来了
{"Root":{Student:{key:Student1,value=4}}}
任何人都可以为此提供帮助
答案 0 :(得分:0)
您可以检测是否存在单个Student
元素,如果是,则在其后添加一个删除了所有属性的元素。然后,您将序列化为JSON并执行简单的String.Replace()
以删除null
条目:
class Program
{
static void Main(string[] args)
{
var singleElement = false;
var x = XDocument
.Parse(@"<Root><Student key=""Student1"" value=""4""/></Root>");
if (x.Root.Elements().Count() == 1)
{
singleElement = true;
var single = x.Root.Elements().First();
x.Root.Elements().First().AddAfterSelf(single);
x.Root.Elements().Last().Attributes().ToList()
.ForEach(a => a.Remove());
//optionally, remove the value, if you expect one
x.Root.Elements().Last().Value = String.Empty;
}
var xml = JsonConvert.SerializeXNode(x);
if (singleElement)
xml = xml.Replace(",null", "");
}
}