1
我正在寻找一种简单的方法来将我的xml转换为json,并使用附加选项将完整xpath添加为属性。现在我做这种方式:简化xml到json转换
private static string XmlToJson(string xmlString)
{
return new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(xmlString)));
}
private static Dictionary<string, object> GetXmlValues(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements)
{
attr.Add("_children", xml.Elements().Select(e => GetXmlValues(e)));
attr.Add("_path", xml.GetPath());
}
else if (!xml.IsEmpty)
{
attr.Add("_value", xml.Value);
attr.Add("_path", xml.GetPath());
}
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
private static string GetPath(this XElement node)
{
string path = node.Name.LocalName;
XElement currentNode = node;
while (currentNode.Parent != null)
{
currentNode = currentNode.Parent;
path = currentNode.Name.LocalName + "/" + path;
}
return path;
}
但它看起来迂回比较:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
但那里我不知道如何皈依过程中添加的路径?
你是不是从XML转换成JSON,您创建一个完全不同的表现与'_value'和'_path '拥有......某些东西的属性。请发布源XML和期望的JSon输出的示例。如果要序列化不同的形状,请在中间步骤(例如,使用LINQ)中执行转换,然后序列化结果 –