我试图将普通的JSON更改为XML,但我不想将JSON的键更改为XML节点,而是希望将其更改为属性。我尝试了以下代码
XNode node = JsonConvert.DeserializeXNode(kvp.ToString(), "root");
但这给了我XML,每个字段都作为节点。
例如,我的JSON是:
"ItemDetails": [
{
"ItemNo": "0001",
"Desc": "Office Supplies",
"Note": "",
"Units": "20"
}
]
我想将其更改为以下内容。以每个键作为属性,而不是XML节点
<ItemDetails ItemNo="0001" Desc="Office Supplies" Note="" Units="20"/>
答案 0 :(得分:1)
使用Newtonsoft并非开箱即用。相反,您必须创建具有所有节点的XML,然后重写它以将所有节点移至属性,它们将删除子节点。
您可以同时使用XmlDocument
和XNode
XNode示例
string json = @"{
""ItemDetails"": [
{
""ItemNo"": ""0001"",
""Desc"": ""Office Supplies"",
""Note"": """",
""Units"": ""20""
}
]}";
XNode node = JsonConvert.DeserializeXNode(json, "root");
// select all ItemDetails
var itemDetails = node.XPathSelectElements("//ItemDetails");
foreach (XElement item in itemDetails)
{
foreach (XNode childNode in item.Nodes().ToList())
{
// add attribute to node
var element = childNode as XElement;
item.SetAttributeValue(element.Name, element.Value);
// remove the childnode
element.Remove();
}
}
Console.WriteLine(node.Document.ToString());
试运行:https://dotnetfiddle.net/EVDwHN
XmlDocument示例
string json = @"{
""ItemDetails"": [
{
""ItemNo"": ""0001"",
""Desc"": ""Office Supplies"",
""Note"": """",
""Units"": ""20""
}
]}";
// using xmldocument
XmlDocument doc = JsonConvert.DeserializeXmlNode(json, "root", true);
// select all ItemDetails
var itemDetails = doc.SelectNodes("//ItemDetails");
foreach (XmlNode item in itemDetails)
{
foreach (XmlNode childNode in item.ChildNodes.Cast<XmlNode>().ToList())
{
var attribute = doc.CreateAttribute(childNode.Name);
attribute.Value = childNode.InnerText;
// add attribute to node
item.Attributes.Append(attribute);
// remove the childnode
item.RemoveChild(childNode);
}
}
Console.WriteLine(doc.InnerXml);