1 // ================================================================================================
3 // ページのXML要素をあらわすモデルクラスソース</summary>
5 // <copyright file="XmlElement.cs" company="honeplusのメモ帳">
6 // Copyright (C) 2011 Honeplus. All rights reserved.</copyright>
9 // ================================================================================================
11 namespace Honememo.Parsers
14 using System.Collections.Generic;
17 using Honememo.Utilities;
20 /// ページのXML要素をあらわすモデルクラスです。
22 /// <remarks>解析処理は複雑なため、<see cref="XmlParser"/>として別途実装。</remarks>
23 public class XmlElement : ListElement
37 /// 指定されたタグ名・属性・値からXML要素を生成する。
39 /// <param name="name">タグ名。</param>
40 /// <param name="attributes">属性。</param>
41 /// <param name="innerElements">値。</param>
42 /// <param name="parsedString">Parse解析時の元の文字列。</param>
45 IDictionary<string, string> attributes,
46 ICollection<IElement> innerElements,
47 string parsedString = null)
50 this.ParsedString = parsedString;
51 if (attributes != null)
53 this.Attributes = new Dictionary<string, string>(attributes);
57 this.Attributes = new Dictionary<string, string>();
60 if (innerElements != null)
62 this.AddRange(innerElements);
67 /// 指定されたタグ名・値からXML要素を生成する。
69 /// <param name="name">タグ名。</param>
70 /// <param name="value">値。未指定時は<c>null</c>。</param>
71 public XmlElement(string name, string value = null)
74 this.Attributes = new Dictionary<string, string>();
75 if (!string.IsNullOrEmpty(value))
77 this.Add(new TextElement(value));
88 /// <exception cref="ArgumentNullException">タグ名がnullの場合。</exception>
89 /// <exception cref="ArgumentException">タグ名が空の場合。</exception>
90 public virtual string Name
99 this.name = Validate.NotBlank(value);
106 public virtual IDictionary<string, string> Attributes
117 /// このXML要素を表す文字列を返す。
119 /// <returns>このXML要素を表す文字列。</returns>
120 protected override string ToStringImpl()
122 StringBuilder b = new StringBuilder();
123 XmlWriterSettings s = new XmlWriterSettings();
124 s.CheckCharacters = false;
125 s.ConformanceLevel = ConformanceLevel.Fragment;
126 using (XmlWriter w = XmlWriter.Create(b, s))
128 w.WriteStartElement(this.Name);
129 foreach (KeyValuePair<string, string> attr in this.Attributes)
131 w.WriteAttributeString(attr.Key, attr.Value);
134 foreach (IElement element in this)
136 // エンコードする/しないは中身の責任として、ここではエンコードしない
137 // ※ エンコードするテキストを用意したい場合はXmlTextElementを使うなど
138 w.WriteRaw(element.ToString());