C# Helperクラスを使って、XMLにノードを追加する。
XmlHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XmlOperator { class XmlHelper { public static XmlNode AddElement(string tagName, string textContent, XmlNode parent) { XmlNode node = parent.OwnerDocument.CreateElement(tagName); parent.AppendChild(node); if (textContent != null) { XmlNode content; content = parent.OwnerDocument.CreateTextNode(textContent); node.AppendChild(content); } return node; } public static XmlNode AddAttribute(string attributeName, string textContent, XmlNode parent) { XmlAttribute attribute; attribute = parent.OwnerDocument.CreateAttribute(attributeName); attribute.Value = textContent; parent.Attributes.Append(attribute); return attribute; } } }
Main
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XmlOperator.sample1 { class Program { static void Main(string[] args) { XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode products = doc.CreateElement("productes"); doc.AppendChild(products); XmlNode product = XmlHelper.AddElement("product", null, products); XmlHelper.AddAttribute("id", "100", product); XmlHelper.AddElement("productName", "コーヒー", product); XmlHelper.AddElement("productPrice", "150", product); product = XmlHelper.AddElement("product", null, products); XmlHelper.AddAttribute("id", "110", product); XmlHelper.AddElement("productName", "缶ジュース", product); XmlHelper.AddElement("productPrice", "120", product); doc.Save(Console.Out); Console.ReadLine(); } } }
C#ショートコードプログラミング 第2版 (MSDNプログラミングシリーズ)
- 作者: 川俣晶
- 出版社/メーカー: 日経BP社
- 発売日: 2014/01/17
- メディア: 単行本
- この商品を含むブログ (1件) を見る