LoginSignup
9
9

More than 5 years have passed since last update.

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

Posted at

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#すっげえ。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9