Get document description using xmlreader

C# .NET Core 6: Get rootname, namespace or DTD using xmlreader

using (var stream = new MemoryStream())
{
	FormFile?.CopyTo(stream);
	stream.Seek(0, SeekOrigin.Begin);

	var settings = new XmlReaderSettings()
	{
		// Parse file but do not reolve
		DtdProcessing = DtdProcessing.Parse,
		XmlResolver = null
	};

	using (var reader = XmlReader.Create(stream, settings))
	{
		var done = false;

		while (reader.Read() && !done)
		{
			// something weird happened, bail out
			//if (reader.EOF)
			//	return;

			switch (reader.NodeType)
			{
				// Assume cXML
				case XmlNodeType.DocumentType:
					DocumentType = reader.GetAttribute("SYSTEM") + "";
					break;

				case XmlNodeType.Element:
					switch (reader.LocalName)
					{
						// Assume an UBL dpcument of some kind
						case "CustomizationID":
							reader.Read();
							SetCustomization(reader.Value);
							break;

						// Only OIOUBL, done and exit
						case "UBLlVersionID":
							reader.Read();
							UblVersion = reader.Value;
							done = true;
							break;

						// Only OIOXML, done and exit
						case "TypeCode":
							reader.Read();
							TypeCode = reader.Value;
							done = true;
							break;

						default:
							if (string.IsNullOrEmpty(RootName))
							{
								RootName = reader.Name;
								SetNamespace(reader.NamespaceURI);
							}
							break;
					}
					break;
			}
		}
		reader.Close();
	}
}



Comments are closed