XmlFormatReader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Xml;
  5. namespace Google.ProtocolBuffers.Serialization
  6. {
  7. /// <summary>
  8. /// Parses a proto buffer from an XML document or fragment. .NET 3.5 users may also
  9. /// use this class to process Json by setting the options to support Json and providing
  10. /// an XmlReader obtained from <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory"/>.
  11. /// </summary>
  12. public class XmlFormatReader : AbstractTextReader
  13. {
  14. public const string DefaultRootElementName = XmlFormatWriter.DefaultRootElementName;
  15. private readonly XmlReader _input;
  16. private string _rootElementName;
  17. private static XmlReaderSettings DefaultSettings
  18. {
  19. get
  20. {
  21. return new XmlReaderSettings()
  22. {CheckCharacters = false, IgnoreComments = true, IgnoreProcessingInstructions = true};
  23. }
  24. }
  25. /// <summary>
  26. /// Constructs the XmlFormatReader using the stream provided as the xml
  27. /// </summary>
  28. public static XmlFormatReader CreateInstance(byte[] input)
  29. {
  30. return new XmlFormatReader(XmlReader.Create(new MemoryStream(input, false), DefaultSettings));
  31. }
  32. /// <summary>
  33. /// Constructs the XmlFormatReader using the stream provided as the xml
  34. /// </summary>
  35. public static XmlFormatReader CreateInstance(Stream input)
  36. {
  37. return new XmlFormatReader(XmlReader.Create(input, DefaultSettings));
  38. }
  39. /// <summary>
  40. /// Constructs the XmlFormatReader using the string provided as the xml to be read
  41. /// </summary>
  42. public static XmlFormatReader CreateInstance(String input)
  43. {
  44. return new XmlFormatReader(XmlReader.Create(new StringReader(input), DefaultSettings));
  45. }
  46. /// <summary>
  47. /// Constructs the XmlFormatReader using the xml in the TextReader
  48. /// </summary>
  49. public static XmlFormatReader CreateInstance(TextReader input)
  50. {
  51. return new XmlFormatReader(XmlReader.Create(input, DefaultSettings));
  52. }
  53. /// <summary>
  54. /// Constructs the XmlFormatReader with the XmlReader
  55. /// </summary>
  56. public static XmlFormatReader CreateInstance(XmlReader input)
  57. {
  58. return new XmlFormatReader(input);
  59. }
  60. /// <summary>
  61. /// Constructs the XmlFormatReader with the XmlReader and options
  62. /// </summary>
  63. protected XmlFormatReader(XmlReader input)
  64. {
  65. _input = input;
  66. _rootElementName = DefaultRootElementName;
  67. Options = XmlReaderOptions.None;
  68. }
  69. /// <summary>
  70. /// Constructs the XmlFormatReader with the XmlReader and options
  71. /// </summary>
  72. protected XmlFormatReader(XmlFormatReader copyFrom, XmlReader input)
  73. : base(copyFrom)
  74. {
  75. _input = input;
  76. _rootElementName = copyFrom._rootElementName;
  77. Options = copyFrom.Options;
  78. }
  79. /// <summary>
  80. /// Gets or sets the options to use when reading the xml
  81. /// </summary>
  82. public XmlReaderOptions Options { get; set; }
  83. /// <summary>
  84. /// Sets the options to use while generating the XML
  85. /// </summary>
  86. public XmlFormatReader SetOptions(XmlReaderOptions options)
  87. {
  88. Options = options;
  89. return this;
  90. }
  91. /// <summary>
  92. /// Gets or sets the default element name to use when using the Merge&lt;TBuilder>()
  93. /// </summary>
  94. public string RootElementName
  95. {
  96. get { return _rootElementName; }
  97. set
  98. {
  99. ThrowHelper.ThrowIfNull(value, "RootElementName");
  100. _rootElementName = value;
  101. }
  102. }
  103. private XmlFormatReader CloneWith(XmlReader rdr)
  104. {
  105. XmlFormatReader copy = new XmlFormatReader(this, rdr);
  106. return copy;
  107. }
  108. private void NextElement()
  109. {
  110. while (!_input.IsStartElement() && _input.Read())
  111. {
  112. continue;
  113. }
  114. }
  115. private static void Assert(bool cond)
  116. {
  117. if (!cond)
  118. {
  119. throw new FormatException();
  120. }
  121. }
  122. /// <summary>
  123. /// Reads the root-message preamble specific to this formatter
  124. /// </summary>
  125. public override AbstractReader ReadStartMessage()
  126. {
  127. return ReadStartMessage(_rootElementName);
  128. }
  129. public AbstractReader ReadStartMessage(string element)
  130. {
  131. string field;
  132. Assert(PeekNext(out field) && field == element);
  133. XmlReader child = _input.ReadSubtree();
  134. while (!child.IsStartElement() && child.Read())
  135. {
  136. continue;
  137. }
  138. child.Read();
  139. return CloneWith(child);
  140. }
  141. /// <summary>
  142. /// Reads the root-message close specific to this formatter, MUST be called
  143. /// on the reader obtained from ReadStartMessage(string element).
  144. /// </summary>
  145. public override void ReadEndMessage()
  146. {
  147. Assert(0 == _input.Depth);
  148. if(_input.NodeType == XmlNodeType.EndElement)
  149. {
  150. _input.Read();
  151. }
  152. }
  153. /// <summary>
  154. /// Merge the provided builder as an element named <see cref="RootElementName"/> in the current context
  155. /// </summary>
  156. public override TBuilder Merge<TBuilder>(TBuilder builder, ExtensionRegistry registry)
  157. {
  158. return Merge(_rootElementName, builder, registry);
  159. }
  160. /// <summary>
  161. /// Merge the provided builder as an element of the current context
  162. /// </summary>
  163. public TBuilder Merge<TBuilder>(string element, TBuilder builder) where TBuilder : IBuilderLite
  164. {
  165. return Merge(element, builder, ExtensionRegistry.Empty);
  166. }
  167. /// <summary>
  168. /// Merge the provided builder as an element of the current context
  169. /// </summary>
  170. public TBuilder Merge<TBuilder>(string element, TBuilder builder, ExtensionRegistry registry)
  171. where TBuilder : IBuilderLite
  172. {
  173. string field;
  174. Assert(PeekNext(out field) && field == element);
  175. ReadMessage(builder, registry);
  176. return builder;
  177. }
  178. /// <summary>
  179. /// Peeks at the next field in the input stream and returns what information is available.
  180. /// </summary>
  181. /// <remarks>
  182. /// This may be called multiple times without actually reading the field. Only after the field
  183. /// is either read, or skipped, should PeekNext return a different value.
  184. /// </remarks>
  185. protected override bool PeekNext(out string field)
  186. {
  187. NextElement();
  188. if (_input.IsStartElement())
  189. {
  190. field = _input.LocalName;
  191. return true;
  192. }
  193. field = null;
  194. return false;
  195. }
  196. /// <summary>
  197. /// Causes the reader to skip past this field
  198. /// </summary>
  199. protected override void Skip()
  200. {
  201. if (_input.IsStartElement())
  202. {
  203. if (!_input.IsEmptyElement)
  204. {
  205. int depth = _input.Depth;
  206. while (_input.Depth >= depth && _input.NodeType != XmlNodeType.EndElement)
  207. {
  208. Assert(_input.Read());
  209. }
  210. }
  211. _input.Read();
  212. }
  213. }
  214. /// <summary>
  215. /// returns true if it was able to read a single value into the value reference. The value
  216. /// stored may be of type System.String, System.Int32, or an IEnumLite from the IEnumLiteMap.
  217. /// </summary>
  218. protected override bool ReadEnum(ref object value)
  219. {
  220. int number;
  221. string temp;
  222. if (null != (temp = _input.GetAttribute("value")) && int.TryParse(temp, out number))
  223. {
  224. Skip();
  225. value = number;
  226. return true;
  227. }
  228. return base.ReadEnum(ref value);
  229. }
  230. /// <summary>
  231. /// Returns true if it was able to read a String from the input
  232. /// </summary>
  233. protected override bool ReadAsText(ref string value, Type type)
  234. {
  235. Assert(_input.NodeType == XmlNodeType.Element);
  236. value = _input.ReadElementContentAsString();
  237. return true;
  238. }
  239. /// <summary>
  240. /// Merges the input stream into the provided IBuilderLite
  241. /// </summary>
  242. protected override bool ReadMessage(IBuilderLite builder, ExtensionRegistry registry)
  243. {
  244. Assert(_input.IsStartElement());
  245. if (!_input.IsEmptyElement)
  246. {
  247. int depth = _input.Depth;
  248. XmlReader child = _input.ReadSubtree();
  249. while (!child.IsStartElement() && child.Read())
  250. {
  251. continue;
  252. }
  253. child.Read();
  254. builder.WeakMergeFrom(CloneWith(child), registry);
  255. Assert(depth == _input.Depth && _input.NodeType == XmlNodeType.EndElement);
  256. }
  257. _input.Read();
  258. return true;
  259. }
  260. private IEnumerable<string> NonNestedArrayItems(string field)
  261. {
  262. return base.ForeachArrayItem(field);
  263. }
  264. /// <summary>
  265. /// Cursors through the array elements and stops at the end of the array
  266. /// </summary>
  267. protected override IEnumerable<string> ForeachArrayItem(string field)
  268. {
  269. bool isNested = (Options & XmlReaderOptions.ReadNestedArrays) != 0;
  270. if (!isNested)
  271. {
  272. foreach (string item in NonNestedArrayItems(field))
  273. {
  274. yield return item;
  275. }
  276. yield break;
  277. }
  278. if (!_input.IsEmptyElement)
  279. {
  280. int depth = _input.Depth;
  281. XmlReader child = _input.ReadSubtree();
  282. while (!child.IsStartElement() && child.Read())
  283. {
  284. continue;
  285. }
  286. child.Read();
  287. foreach (string item in CloneWith(child).NonNestedArrayItems("item"))
  288. {
  289. yield return item;
  290. }
  291. Assert(depth == _input.Depth && _input.NodeType == XmlNodeType.EndElement);
  292. }
  293. _input.Read();
  294. yield break;
  295. }
  296. }
  297. }