LINQ to Xml による XML ファイルの生成
LINQ to Xml を使用すると、簡単にXMLファイルを作成することができます。
VBの例
Imports System.Xml.Linq Dim XDoc = New XDocument(New XDeclaration("1.0", "utf-8", True), New XElement("Employee", New XElement("Name"), New XElement("Dept"), New XElement("Salary"))) XDoc.Save("C:\Work\Employee.xml")
C#の例
using System.Xml.Linq; var XDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement("Employee", new XElement("Name"), new XElement("Dept"), new XElement("Salary"))); XDoc.Save(@"C:\Work\Employee.xml");
■必要な名前空間
LINQ to XMLを使用するには、VBの場合は Imports System.Xml.Linq 、C#の場合は using System.Xml.Linqが必要です。
XmlDocumentの作成と定義の設定
次に、XmlDocumentを作成するには、XDocumentクラスを使用します。
XMLドキュメントの定義部部分は XDeclaretionクラスで作成します。引数には、バージョン、文字コード、スタンドアローンステータス(trueまたはfalse)を指定します。
■要素の作成
要素は、XElementクラスを使用します。入れ子の要素を作成する場合は、XElementクラスのコンストラクタの第2引数以下に、さらにXElementを指定します。
上記の例では、Employee要素の中に。Name, Dept, Saalryの3つの要素を指定しています。
■保存
作成した XDocumentはSaveメソッドで保存することができます。
Saveメソッドの引数には保存先パスを指定します。
Please follow and like us:
コメント