Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
8
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@hirocueki2

C#でXMLをJSONにコンバート(最短・エラーチェックなし)

xmlをjsonにしたいことってありますよね。でもサクッとやる方法がおもいつかず。。困っていたんですが。

C#、もといアンダース・ヘルスバーグならなんとかしてくれる。

と信じて書いてみたら3行で望みの結果を得られた。

環境

  • VisualStudio 2015
xmltojson.cs
using Newtonsoft.Json;
using System.IO;
using System.Xml;

namespace Lib
{
    class XmlToJson
    {
        static public void ToJson(string path_to_xml, string path_to_json)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(File.ReadAllText(path_to_xml));
            File.WriteAllText(path_to_json, JsonConvert.SerializeXmlNode(doc));
        }
    }
}
Usage
static void Main(string[] args)
{
    XmlToJson.ToJson("hoge.xml", "hoge.json");
}
変換元のxml
<?xml version="1.0" encoding="utf-8"?>
<persons>
  <person id="1">
    <firstname>イチキータ</firstname>
    <lastname>山田</lastname>
    <birthday>2001/10/01</birthday>
  </person>
  <person id="2">
    <firstname>ニキータ</firstname>
    <lastname>山田</lastname>
    <birthday>2004/11/09</birthday>
  </person>
</persons>
変換後のjson
{
  "?xml": {
    "@version": "1.0",
    "@encoding": "utf-8"
  },
  "persons": {
    "person": [
      {
        "@id": "1",
        "firstname": "イチキータ",
        "lastname": "山田",
        "birthday": "2001/10/01"
      },
      {
        "@id": "2",
        "firstname": "ニキータ",
        "lastname": "山田",
        "birthday": "2004/11/09"
      }
    ]
  }

}

所感

C#すっげえ。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
8
Help us understand the problem. What are the problem?