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);
しかしそこに、私はどのようにconvertionの間にパスを追加するには考えているために今、私はそれがこの方法を行いますか?
あなたはJSONにXMLから変換されていない、あなたは '_value'と' _pathと完全に異なる表現を作成します'何かを保持する属性。ソースXMLと望ましいJSon出力の例を投稿してください。別のシェイプをシリアル化する場合は、中間ステップで変換を実行し(たとえばLINQを使用)、結果をシリアライズします –