XmlDocumentクラスを使用することで、XMLの作成や読み込みを容易に行えます。
| メソッド | 機能 |
|---|---|
| Save(String) | 指定のファイルに書き込む |
| Load(String) | 指定のURLから読み込む |
| LoadXml(String) | 指定の文字列から読み込む |
public virtual void Save (string filename);Save(String) - XmlDocument.Save Method (System.Xml) | Microsoft Learn
XmlDocument document = new XmlDocument();
XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "utf-8", null); // XML宣言
XmlElement root = document.CreateElement("root");
document.AppendChild(declaration);
document.AppendChild(root);
XmlElement e1 = document.CreateElement("e1");
XmlElement e2 = document.CreateElement("e2");
e1.SetAttribute("a1", "10"); // 属性
e2.SetAttribute("a2", "20"); // 属性
root.AppendChild(e1);
root.AppendChild(e2);
XmlElement e3 = document.CreateElement("e3");
XmlText v3 = document.CreateTextNode("ABC");
e3.SetAttribute("a3", "30");
e3.AppendChild(v3);
e2.AppendChild(e3);
// ファイルに保存する
document.Save("sample.xml");
このコードは、次のようなファイルを出力します。
<?xml version="1.0" encoding="utf-8"?>
<root>
<e1 a1="10" />
<e2 a2="20">
<e3 a3="30">ABC</e3>
</e2>
</root>
このとき既定でBOMありのUTF-8となるため、BOMなしとしたければEncodingを指定したStreamを介して書き込みます。xml - How can I remove the BOM from XmlTextWriter using C#? - Stack Overflow
XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false); using (XmlWriter writer = XmlWriter.Create("sample.xml", settings)) { document.Save(writer); }
public virtual void Load (string filename);Load(String) - XmlDocument.Load Method (System.Xml) | Microsoft Learn
XmlDocument document = new XmlDocument(); // ファイルから読み込む document.Load("sample.xml"); XmlElement root = document.DocumentElement; XmlElement e1 = (XmlElement)root.ChildNodes[0]; XmlElement e2 = (XmlElement)root.ChildNodes[1]; string a1 = e1.GetAttribute("a1"); // "10" string a2 = e2.GetAttribute("a2"); // "20" bool b1 = e1.HasChildNodes; // false bool b2 = e2.HasChildNodes; // true XmlElement e3 = (XmlElement)e2.FirstChild; string a3 = e3.GetAttribute("a3"); // "30" XmlNode n3 = e3.FirstChild; string v3 = n3.Value; // "ABC"
public virtual void LoadXml (string xml);XmlDocument.LoadXml(String) Method (System.Xml) | Microsoft Learn
XmlDocument document = new XmlDocument();
document.LoadXml("<A><B>C</B></A>");
XML宣言のノードを作成できます。
public virtual System.Xml.XmlDeclaration CreateXmlDeclaration (
hstring version, // バージョン。必ず"1.0"
string encoding, // エンコーディング属性の値
string standalone // スタンドアロン属性の値。"yes"または"no"
);
XmlDocument.CreateXmlDeclaration(String, String, String) Method (System.Xml) | Microsoft Learn