Created
July 20, 2012 21:07
-
-
Save thinkAmi/3153229 to your computer and use it in GitHub Desktop.
MBSAのXMLファイルからLINQ to XMLを使ってCSVファイルへと出力するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Xml.Linq; | |
namespace MBSAToCSV | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string xmlFilePath = ""; | |
if (args.Any()) | |
{ | |
xmlFilePath = args.First(); | |
} | |
else | |
{ | |
xmlFilePath = @"<デフォルトのXMLファイルパス>"; | |
} | |
if (System.IO.File.Exists(xmlFilePath)) { } | |
else | |
{ | |
Console.WriteLine("ファイルがありません。"); | |
return; | |
} | |
var csv = System.Xml.Linq.XElement.Load(xmlFilePath).Elements("Check").Elements("Detail").Elements("UpdateData") | |
.Where(a => a.Attribute("IsInstalled").Value == "false") | |
.Select(b => string.Format("{0},{1},{2},{3}{4}", | |
(string)b.Attribute("ID"), | |
"KB" + (string)b.Attribute("KBID"), | |
(string)b.Element("Title"), | |
(string)b.Element("References").Element("InformationURL"), | |
Environment.NewLine | |
)) | |
.Aggregate(new StringBuilder(), (sb, s) => sb.Append(s), sb => sb.ToString()); | |
// 拡張子をxmlからstringに変換して保存 | |
string csvPath = xmlFilePath.Substring(0, xmlFilePath.Length - 3) + "csv"; | |
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("shift_jis"); | |
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(csvPath, false, enc)) | |
{ | |
// ヘッダーの先頭にID列を表記したい場合はダブルコーテーションで囲む | |
// See: http://pasofaq.jp/office/excel/sylk.htm | |
string header = "\"ID\",KB番号,タイトル,情報へのURL"; | |
sw.WriteLine(header); | |
sw.WriteLine(csv); | |
} | |
Console.WriteLine("出力しました。"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment