【发布时间】:2020-05-06 02:30:35
【问题描述】:
我先将一个对象转换为json,然后再将json转换为xml。我需要这样做来生成一些属性作为 xml 属性而不是元素。一切都按预期工作,只是我无法为每个项目生成单独的 xml 元素。
C#代码:
string json = JsonConvert.SerializeObject(myObj);
XmlDocument xdoc = JsonConvert.DeserializeXmlNode(json, "root");
生成的json:
{
"header": "myheader",
"transaction": {
"date": "2019-09-24",
"items": [
{
"number": "123",
"unit": "EA",
"qty": 6
},
{
"number": "456",
"unit": "CS",
"qty": 4
}
]
}
}
C# 类:
public class Item
{
[JsonProperty("@number")]
public string number { get; set; }
[JsonProperty("@unit")]
public string unit { get; set; }
[JsonProperty("@qty")]
public int qty { get; set; }
}
public class Transaction
{
[JsonProperty("@date")]
public string date { get; set; }
public List<Item> items { get; set; }
}
public class Root
{
public string header { get; set; }
public Transaction transaction { get; set; }
}
生成的(不需要的)输出:
<root>
<header>string</header>
<transaction date="string">
<items number="string" unit="string" qty="0"/>
<items number="string" unit="string" qty="0"/>
</transaction>
</root>
预期输出:
<root>
<header>string</header>
<transaction date="string">
<items>
<item number="string" unit="string" qty="0"/>
<item number="string" unit="string" qty="0"/>
</items>
</transaction>
</root>
【问题讨论】:
-
我认为下面的讨论应该对你有所帮助。 stackoverflow.com/questions/38726166/…
-
它有帮助。它按预期工作。
标签: c# json xml jsonconvert