我有一个像下面这样的json
{
"Title": null,
"ProjectName": {
"@Label": "Project Name",
"Value": "",
"@Template": ""
},
"ModelNo": {
"@Label": "Model",
"Value": "",
"@Template": ""
}
}
我想将其转换为 xml,如下所示:
<Root>
<Title>Test Title</Title>
<ProjectName Label="Project Name" Template="">Test Project Name</ProjectName>
<ModelNo Label="Model" Template="">Test Model Number</ModelNo>
</Root>
目前我用了
JsonConvert.DeserializeXmlNode(Json.ToString())
的东西,加上XmlAttribute
,结果就是
<Root>
<Title>Test Title</Title>
<ProjectName Label="Project Name" Template=""><Value>Test Project Name</Value></ProjectName>
<ModelNo Label="Model" Template=""><Value>Test Model Number</Value></ModelNo>
</Root>
如何确保没有
Value
,并将Value映射到xml文本
您可以通过 LINQ to JSON API 替换/构建新的 JSON。例如(假设源值在 JSON 中,否则分析和操作
jp.Value
):
var js = """
{
"Title": "Test Title",
"ProjectName": {
"@Label": "Project Name",
"Value": "Test Project Name",
"@Template": ""
},
"ModelNo": {
"@Label": "Model",
"Value": "Test Model",
"@Template": ""
}
}
""";
var jObject = JObject.Parse(js);
var jsonProperties = jObject.Descendants()
.OfType<JProperty>()
.Where(jp => jp.Name == "Value")
.ToList();
foreach (JProperty jp in jsonProperties)
{
// replace "Value" with "#text" property name
jp.Replace(new JProperty("#text", jp.Value));
}
var deserializeXmlNode = JsonConvert.DeserializeXmlNode(jObject.ToString(), "Root");
Console.WriteLine(deserializeXmlNode.OuterXml);