2

以下は、JSON 応答のタイプです。

{
  "?xml":{
    "@version":"1.0",
    "@encoding":"iso-8859-1"
  },
  "xmlreport":{
    "@title":"ABC: TEST Most Saved2",
    "@dates":"Week of May 19,2013",
    "columns":{
      "column":[
        {
          "@name":"Page",
          "@type":"dimension",
          "#text":"Page"
        },
        {
          "@name":"Events",
          "@type":"metric",
          "@hastotals":"true",
          "#text":"Events"
        }
      ]
    },
    "rows":{
      "row":[
        {
          "@rownum":"1",
          "cell":[
            {
              "@columnname":"page",
              "@csv":"\"http://www.ABC.com/profile/recipebox\"",
              "#text":"http://www.ABC.com/profile/recipebox"
            },
            {
              "@columnname":"events",
              "@percentage":"\"0.1%\"",
              "#text":"489"
            }
          ]
        },
        {
          "@rownum":"2",
          "cell":[
            {
              "@columnname":"page",
              "@csv":"\"http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\"",
              "#text":"http://www.ABC.com/recip...c602e4-007b-43e0-aaab-2f9aed89524c"
            },
            {
              "@columnname":"events",
              "@percentage":"\"0.0%\"",
              "#text":"380"
            }
          ]
        }
      ]
    },
    "totals":{
      "pagetotals":{
        "total":{
          "@columnname":"events",
          "@value":"1820.000000",
          "#text":"1,820 (0.2%)"
        }
      },
      "reporttotals":{
        "total":{
          "@columnname":"events",
          "@value":"7838.000000",
          "#text":"7,838 (0.8%)"
        }
      },
      "timeperiodtotals":{
        "total":{
          "@columnname":"events",
          "@value":"955774.000000",
          "#text":"955,774 (100.0%)"
        }
      }
    }
  }
}

オブジェクトを解析できません。解析後に属性と要素を読み取る方法を教えてください。私はC#を使用しています

{ 
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(XML);

     string jsonText = JsonConvert.SerializeXmlNode(doc);
     //var result = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(jsonText, "xmlreport");
     var results = JsonConvert.DeserializeObject<dynamic>(jsonText);

     JToken token = JObject.Parse(jsonText);
     var report = token["xmlreport"];
}
4

3 に答える 3

1

質問に対する私の理解は、Xml がいくつかあり、json を送信する必要があるということです。コードに入る前のいくつかのポイント:

1) 問題が発生するため、xml を json に直接変換しないでください。

2) 最後に xml をオブジェクトに解析し、返す形式を決定します。出入りするものを切り離すことで、マッピングを微調整できるため、インターフェイスの 1 つを変更しても、他のインターフェイスに影響を与えることなく変更できます。

だから、コードに...

基本的に、xml をオブジェクトに解析して、さらに処理できるようにしてから、json としてプッシュします。

class Program
{
    private static string starting =
        "<xmlreport title=\"ABC: TEST Most Saved2\" dates=\"Week of May 19,2013\"><columns><column name=\"Page\" type=\"dimension\">Page</column><column name=\"Events\" type=\"metric\" hastotals=\"true\">Events</column></columns><rows><row rownum=\"1\"><cell columnname=\"page\" csv=\"http://www.ABC.com/profile/recipebox\">http://www.ABC.com/profile/recipebox</cell><cell columnname=\"events\" percentage=\"0.1%\">489</cell></row><row rownum=\"2\"><cell columnname=\"page\" csv=\"http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\">http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c</cell><cell columnname=\"events\" percentage=\"0.0%\">380</cell></row></rows><totals><pagetotals><total columnname=\"events\" value=\"1820.00000\">1,820 (0.2%)</total></pagetotals><reporttotals><total columnname=\"events\" value=\"7838.000000\">7,838 (0.8%)</total></reporttotals><timeperiodtotals><total columnname=\"events\" value=\"955774.000000\">955,774 (100.0%)</total></timeperiodtotals></totals></xmlreport>";


    static void Main(string[] args)
    {
        // parse from xml to objects
        StringReader reader = new StringReader(starting);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(XmlReport));
        var xmlreport = (XmlReport)xmlSerializer.Deserialize(reader);

        // todo: do some process mapping ...

        // parse out as json
        var json = JsonConvert.SerializeObject(xmlreport);

        Console.WriteLine(json);
        Console.ReadLine();
    }
}

[Serializable]
[XmlRoot(ElementName = "xmlreport")]
public class XmlReport
{
    [XmlAttribute(AttributeName = "title")]
    public string Title { get; set; }
    [XmlAttribute(AttributeName = "dates")]
    public string Dates { get; set; }

    [XmlArray(ElementName = "columns")]
    [XmlArrayItem(typeof(Column), ElementName = "column")]
    public Collection<Column> Columns { get; set; }
}

[Serializable]
public class Column
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "type")]
    public string Type { get; set; }
}

最初にjsonを元のxmlに解析しようとしたので、正しく解釈しなかった場合は謝罪します。構造全体を作成したわけではありませんが、上記の例で残りの作業を行う方法を理解していただければ幸いです。

お役に立てれば。

于 2013-05-31T08:59:39.887 に答える
0

これ (JSON.NET) を使用すると、再帰関数がすべてのキーと値を出力ウィンドウに書き込みます。

        [TestMethod]
        public void ParseMePlease()
        {


            string s = @"{""?xml"":{""@version"":""1.0"",""@encoding"":""iso-8859-1""},
                            ""xmlreport"":{""@title"":""ABC: TEST Most Saved2"",""@dates"":""Week of May 19,2013"",
                            ""columns"":{""column"":[{""@name"":""Page"",""@type"":""dimension"",""#text"":""Page""},{""@name"":""Events"",""@type"":""metric"",""@hastotals"":""true"",""#text"":""Events""}]},
                            ""rows"":
                            {""row"":[{""@rownum"":""1"",""cell"":[{""@columnname"":""page"",""@csv"":""\""http://www.ABC.com/profile/recipebox\"""",""#text"":""http://www.ABC.com/profile/recipebox""},{""@columnname"":""events"",""@percentage"":""\""0.1%\"""",""#text"":""489""}]},
                            {""@rownum"":""2"",""cell"":[{""@columnname"":""page"",""@csv"":""\""http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\"""",""#text"":""http://www.ABC.com/recip...c602e4-007b-43e0-aaab-2f9aed89524c""},{""@columnname"":""events"",""@percentage"":""\""0.0%\"""",""#text"":""380""}]}]},
                            ""totals"":{""pagetotals"":{""total"":{""@columnname"":""events"",""@value"":""1820.000000"",""#text"":""1,820 (0.2%)""}},
                            ""reporttotals"":{""total"":{""@columnname"":""events"",""@value"":""7838.000000"",""#text"":""7,838 (0.8%)""}},
                            ""timeperiodtotals"":{""total"":{""@columnname"":""events"",""@value"":""955774.000000"",""#text"":""955,774 (100.0%)""}}}}}";         
            var result=JsonConvert.DeserializeObject<object>(s);

            Debug.WriteLine("Right Click Result on quick watch for Result Views!(On Debug)"+result.ToString() );

            JObject jobject = ((Newtonsoft.Json.Linq.JObject)result);


            PrintDetail(jobject);

        }

        public void PrintDetail(JObject node)
        {
            foreach (var item in node)
            {                    
                Debug.WriteLine("Key:" + item.Key + " Value:" + item.Value);
                if (item.Value is JObject)
                {
                    PrintDetail((JObject)item.Value);
                }
            }
        }
于 2013-05-31T07:39:30.267 に答える