Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 简化xml到json的转换_C#_Json_Xml - Fatal编程技术网

C# 简化xml到json的转换

C# 简化xml到json的转换,c#,json,xml,C#,Json,Xml,我正在寻找一种简单的方法来将xml转换为json,并添加一个附加选项来添加完整的xpath属性。现在我这样做: private static string XmlToJson(string xmlString) { return new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(xmlString))); } private static

我正在寻找一种简单的方法来将xml转换为json,并添加一个附加选项来添加完整的xpath属性。现在我这样做:

  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;
        }
但是在转换过程中,我不知道如何添加路径

但与之相比,它看起来很迂回

Json.net使用它自己的命名的实现。因此,如果您希望它看起来不迂回,您可以实现并使用它:

var doc = XDocument.Parse(xml);
var json = JsonConvert.SerializeObject(doc, new MyXmlWithXPathJsonConverter());
这是一项不错但相当复杂的任务

但一种更简单的方法是在序列化之前使用xpath属性附加xml节点。例如:

public void AppendXPath(XContainer container)
{
    if (container == null)
        throw new ArgumentNullException("container");

    var doc = container as XDocument;
    if (doc != null)
        AppendXPath(doc.Root, "", 1);
    else
        AppendXPath(container as XElement, "/", 1);
}

private void AppendXPath(XElement node, string parent, int num)
{
    var path = $"{parent}/{node.Name}[{num}]";

    if (node.Attribute("xpath") != null)
        throw new InvalidOperationException($"Node {path} already contains xpath attribute");

    var indicies = new Dictionary<XName, int>();

    foreach (var child in node.Elements())
    {
        int index;
        if (indicies.TryGetValue(child.Name, out index))
            indicies[child.Name] = ++index;
        else
            indicies[child.Name] = index = 1;

        AppendXPath(child, path, index);
    }

    node.Add(new XAttribute("xpath", path));
}
但与之相比,它看起来很迂回

Json.net使用它自己的命名的实现。因此,如果您希望它看起来不迂回,您可以实现并使用它:

var doc = XDocument.Parse(xml);
var json = JsonConvert.SerializeObject(doc, new MyXmlWithXPathJsonConverter());
这是一项不错但相当复杂的任务

但一种更简单的方法是在序列化之前使用xpath属性附加xml节点。例如:

public void AppendXPath(XContainer container)
{
    if (container == null)
        throw new ArgumentNullException("container");

    var doc = container as XDocument;
    if (doc != null)
        AppendXPath(doc.Root, "", 1);
    else
        AppendXPath(container as XElement, "/", 1);
}

private void AppendXPath(XElement node, string parent, int num)
{
    var path = $"{parent}/{node.Name}[{num}]";

    if (node.Attribute("xpath") != null)
        throw new InvalidOperationException($"Node {path} already contains xpath attribute");

    var indicies = new Dictionary<XName, int>();

    foreach (var child in node.Elements())
    {
        int index;
        if (indicies.TryGetValue(child.Name, out index))
            indicies[child.Name] = ++index;
        else
            indicies[child.Name] = index = 1;

        AppendXPath(child, path, index);
    }

    node.Add(new XAttribute("xpath", path));
}

您没有从XML转换为Json,而是创建了一个完全不同的表示形式,其中包含
\u value
\u path
属性,这些属性包含。。。某物请发布源XML和所需JSon输出的示例。如果您想序列化不同的形状,请在中间步骤中执行转换(例如使用LINQ),然后序列化结果如果您不想从XML转换为Json,您可以使用保存以下内容的
\u value
\u path
属性创建一个完全不同的表示法。。。某物请发布源XML和所需JSon输出的示例。如果要序列化不同的形状,请在中间步骤中执行转换(例如使用LINQ),然后序列化结果
{
  "xml": {
    "@xpath": "/xml[1]",
    "foo": {
      "@xpath": "/xml[1]/foo[1]",
      "one": {
        "@xpath": "/xml[1]/foo[1]/one[1]"
      },
      "other": {
        "@xpath": "/xml[1]/foo[1]/other[1]"
      }
    },
    "bar": {
      "@data": "abc",
      "@xpath": "/xml[1]/bar[1]",
      "item": [
        {
          "@order": "3",
          "@xpath": "/xml[1]/bar[1]/item[1]"
        },
        {
          "@order": "1",
          "@xpath": "/xml[1]/bar[1]/item[2]",
          "child": {
            "@whatever": "",
            "@xpath": "/xml[1]/bar[1]/item[2]/child[1]"
          }
        }
      ]
    }
  }
}