Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした