本文整理汇总了C#中System.Xml.XmlReader.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# XmlReader.ReadAsync方法的具体用法?C# XmlReader.ReadAsync怎么用?C# XmlReader.ReadAsync使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Xml.XmlReader
的用法示例。
在下文中一共展示了XmlReader.ReadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateElementSource
private IObservable<XElement> CreateElementSource(XmlReader reader)
{
return Observable.Create<XElement>(async observer =>
{
try
{
reader.MoveToContent();
while (await reader.ReadAsync())
{
if (reader.NodeType == XmlNodeType.Element)
{
var element = XNode.ReadFrom(reader) as XElement;
if (element != null)
{
observer.OnNext(element);
}
}
}
observer.OnCompleted();
}
catch (Exception ex)
{
observer.OnError(ex);
}
});
}
示例2: ConnectAsync
async private Task ConnectAsync(string User, string Password)
{
Socket = await TcpSocket.CreateAndConnectAsync("talk.google.com", 5222);
bool Authenticated = false;
while (true)
{
Console.WriteLine("--------------------------");
await Socket.WriteAsync("<stream:stream to='gmail.com' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' version='1.0'>");
//await Socket.ReadBytesAsync(138);
Reader = XmlReader.Create(Socket.Stream, new XmlReaderSettings() { Async = true, ConformanceLevel = ConformanceLevel.Fragment });
await Reader.ReadAsync(); await Reader.ReadAsync(); Reader = Reader.ReadSubtree(); await Reader.ReadAsync();
var FeaturesXml = await WaitEndElementAsync("stream:features");
var starttls = FeaturesXml.OuterXml.Contains("starttls");
//Console.WriteLine("starttls: {0}", starttls);
//Console.ReadKey();
if (starttls)
{
await Socket.WriteAsync("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
await WaitEndElementAsync("proceed");
await Socket.SecureSslAsync("gmail.com");
Console.WriteLine("StartTLS");
}
else if (!Authenticated)
{
await Socket.WriteAsync(String.Format("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>{0}</auth>", Convert.ToBase64String(Encoding.Default.GetBytes(String.Format("\0{0}\0{1}", User, Password)))));
await WaitEndElementAsync("success");
Authenticated = true;
}
else
{
await Socket.WriteAsync(String.Format("<iq xmlns='jabber:client' type='set' id='1'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>{0}</resource></bind></iq>", "NodeNet"));
var IqNode = await WaitEndElementAsync("iq");
Console.WriteLine(IqNode.OuterXml);
Console.ReadKey();
return;
}
}
}
示例3: ReadXmlAsync
/// <summary>
/// Asynchronously reads data into the current
/// <see cref="SearchResultStream"/>.
/// </summary>
/// <param name="reader">
/// The <see cref="XmlReader"/> from which to read.
/// </param>
/// <returns>
/// A <see cref="Task"/> representing the operation.
/// </returns>
public async Task ReadXmlAsync(XmlReader reader)
{
var fieldNames = new List<string>();
this.FieldNames = new ReadOnlyCollection<string>(fieldNames);
this.IsFinal = true;
if (!await reader.MoveToDocumentElementAsync("results").ConfigureAwait(false))
{
return;
}
string preview = reader.GetRequiredAttribute("preview");
this.IsFinal = !BooleanConverter.Instance.Convert(preview);
if (!await reader.ReadAsync().ConfigureAwait(false))
{
return;
}
reader.EnsureMarkup(XmlNodeType.Element, "meta");
await reader.ReadAsync().ConfigureAwait(false);
reader.EnsureMarkup(XmlNodeType.Element, "fieldOrder");
if (!reader.IsEmptyElement)
{
await reader.ReadEachDescendantAsync("field", async (r) =>
{
await r.ReadAsync().ConfigureAwait(false);
var fieldName = await r.ReadContentAsStringAsync().ConfigureAwait(false);
fieldNames.Add(fieldName);
}).ConfigureAwait(false);
await reader.ReadEndElementSequenceAsync("fieldOrder", "meta").ConfigureAwait(false);
}
if (reader.NodeType == XmlNodeType.Element && reader.Name == "messages")
{
//// Skip messages
await reader.ReadEachDescendantAsync("msg", (r) =>
{
return Task.FromResult(true);
}).ConfigureAwait(false);
reader.EnsureMarkup(XmlNodeType.EndElement, "messages");
await reader.ReadAsync().ConfigureAwait(false);
}
}
示例4: ReadNavigationMapAsync
//Reading navigation map starting from <navMap> node
private static async Task<EpubNavigationMap> ReadNavigationMapAsync(XmlReader reader)
{
EpubNavigationMap result = new EpubNavigationMap();
bool mapFound = await reader.ReadToFollowingAsync("navMap", "http://www.daisy.org/z3986/2005/ncx/");
if (!mapFound)
throw new Exception("EPUB parsing error: navMap section not found in the .toc file.");
//reading till the </navMap> tag appearance
while (await reader.ReadAsync() && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "navMap"))
{
//We are looking for a top-level <navPoint> entries, considering that it could be any level of nesting:
if ((reader.LocalName == "navPoint") && (reader.NodeType != XmlNodeType.EndElement))
{
//We need to create a subreader space to limit the scope for each single navPoint
XmlReader subReader = reader.ReadSubtree();
EpubNavigationPoint navigationPoint = await ReadNavigationPointAsync(subReader);
//we reached the end of the top-level <navPoint> entry and it is time to add it to collection and to get rid of the sub-reader
result.Add(navigationPoint);
subReader.Dispose();
}
}
return result;
}
示例5: ReadMetadataAsync
private static async System.Threading.Tasks.Task<EpubMetadata> ReadMetadataAsync(XmlReader reader, EpubVersion epubVersion)
{
EpubMetadata result = new EpubMetadata();
result.Titles = new List<string>();
result.Creators = new List<EpubMetadataCreator>();
result.Subjects = new List<string>();
result.Publishers = new List<string>();
result.Contributors = new List<EpubMetadataContributor>();
result.Dates = new List<EpubMetadataDate>();
result.Types = new List<string>();
result.Formats = new List<string>();
result.Identifiers = new List<EpubMetadataIdentifier>();
result.Sources = new List<string>();
result.Languages = new List<string>();
result.Relations = new List<string>();
result.Coverages = new List<string>();
result.Rights = new List<string>();
result.MetaItems = new List<EpubMetadataMeta>();
//Parsing all metadata insides and saving it in EpubMetadata instance
//
//Мне нужно пройтись по всем нодам внутри метадаты последовательно, извлечь ноды указанные в массиве metadataNodesNames...
//... и сохранить их в структуре EpubMetadata
//В каждой итерации нам нужно извлечь имя нода, сделать маленькими буквами и,
// в зависимости от того есть ли он в массиве - выполнить запись в структуру
//ИЛИ мы можем тупо искать по заданным в массиве именам, с опасностью, что какая-то сука написала капсами и это ебнет весь ридер
//
bool isMetadataAvailable = await reader.ReadToFollowingAsync("metadata", "http://www.idpf.org/2007/opf");
if (!isMetadataAvailable)
throw new Exception("EPUB parsing error: metadata not found in the package.");
while (await reader.ReadAsync() && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "metadata"))
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
switch (reader.LocalName.ToLowerInvariant())
{
case "title":
result.Titles.Add(reader.ReadElementContentAsString());
break;
case "creator":
EpubMetadataCreator creator = new EpubMetadataCreator();
creator.Role = reader.GetAttribute("opf:role");
creator.FileAs = reader.GetAttribute("opf:file-as");
creator.Creator = reader.ReadElementContentAsString();
result.Creators.Add(creator);
break;
case "subject":
result.Subjects.Add(reader.ReadElementContentAsString());
break;
case "description":
result.Description = reader.ReadElementContentAsString();
break;
case "publisher":
result.Publishers.Add(reader.ReadElementContentAsString());
break;
case "contributor":
EpubMetadataContributor contributor = new EpubMetadataContributor();
contributor.Role = reader.GetAttribute("opf:role");
contributor.FileAs = reader.GetAttribute("opf:file-as");
contributor.Contributor = reader.ReadElementContentAsString();
result.Contributors.Add(contributor);
break;
case "date":
EpubMetadataDate date = new EpubMetadataDate();
date.Event = reader.GetAttribute("opf:event");
date.Date = reader.ReadElementContentAsString();
result.Dates.Add(date);
break;
case "type":
result.Types.Add(reader.ReadElementContentAsString());
break;
case "format":
result.Formats.Add(reader.ReadElementContentAsString());
break;
case "identifier":
EpubMetadataIdentifier identifier = new EpubMetadataIdentifier();
identifier.Id = reader.GetAttribute("id");
identifier.Scheme = reader.GetAttribute("opf:scheme");
identifier.Identifier = reader.ReadElementContentAsString();
result.Identifiers.Add(identifier);
break;
case "source":
result.Sources.Add(reader.ReadElementContentAsString());
break;
case "language":
result.Languages.Add(reader.ReadElementContentAsString());
break;
case "relation":
result.Relations.Add(reader.ReadElementContentAsString());
break;
case "coverage":
result.Coverages.Add(reader.ReadElementContentAsString());
break;
case "rights":
result.Rights.Add(reader.ReadElementContentAsString());
break;
//looks like there is an optional refining node "meta" and it is present in EPUB3
//.........这里部分代码省略.........
示例6: ReadSpineAsync
private static async Task<EpubSpine> ReadSpineAsync(XmlReader reader)
{
EpubSpine result = new EpubSpine();
bool spineFound = await reader.ReadToFollowingAsync("spine", "http://www.idpf.org/2007/opf");
if (!spineFound)
throw new Exception("EPUB parsing error: spine declarations not found in the package.");
if (String.IsNullOrWhiteSpace(reader.GetAttribute("toc")))
throw new Exception("Incorrect EPUB spine: TOC attribute is missing or empty");
result.Toc = reader.GetAttribute("toc");
while (await reader.ReadAsync() && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "spine"))
{
if (reader.LocalName.ToLowerInvariant() == "itemref")
{
EpubSpineItemRef spineItemRef = new EpubSpineItemRef();
spineItemRef.IsLinear = true;
while (reader.MoveToNextAttribute())
{
switch (reader.LocalName.ToLowerInvariant())
{
case "idref":
spineItemRef.IdRef = reader.Value;
break;
case "linear":
if (reader.Value.ToLowerInvariant() == "no")
{
spineItemRef.IsLinear = false;
}
break;
}
}
result.Add(spineItemRef);
}
}
return result;
}
示例7: ParsePropertyValueAsync
static async Task<dynamic> ParsePropertyValueAsync(XmlReader reader, int level)
{
if (reader.IsEmptyElement)
{
await reader.ReadAsync();
return null;
}
string name = reader.Name;
dynamic value;
await reader.ReadAsync();
switch (reader.NodeType)
{
default:
value = await reader.ReadContentAsStringAsync();
break;
case XmlNodeType.Element:
// TODO: rewrite
switch (reader.Name)
{
case "s:dict":
value = await ParseDictionaryAsync(reader, level);
break;
case "s:list":
value = await ParseListAsync(reader, level);
break;
default: throw new InvalidDataException(); // TODO: Diagnostics : unexpected start tag
}
break;
case XmlNodeType.EndElement:
reader.EnsureMarkup(XmlNodeType.EndElement, name);
value = null;
break;
}
reader.EnsureMarkup(XmlNodeType.EndElement, name);
await reader.ReadAsync();
return value;
}
示例8: ParseDictionaryAsync
static async Task<dynamic> ParseDictionaryAsync(XmlReader reader, int level)
{
var value = (IDictionary<string, dynamic>)new ExpandoObject();
if (!reader.IsEmptyElement)
{
await reader.ReadAsync();
while (reader.NodeType == XmlNodeType.Element && reader.Name == "s:key")
{
string name = reader.GetAttribute("name");
// TODO: Include a domain-specific name translation capability (?)
if (level == 0)
{
switch (name)
{
case "action.email.subject.alert":
name = "action.email.subject_alert";
break;
case "action.email.subject.report":
name = "action.email.subject_report";
break;
case "action.email":
case "action.populate_lookup":
case "action.rss":
case "action.script":
case "action.summary_index":
case "alert.suppress":
case "auto_summarize":
name += ".IsEnabled";
break;
case "alert_comparator":
name = "alert.comparator";
break;
case "alert_condition":
name = "alert.condition";
break;
case "alert_threshold":
name = "alert.threshold";
break;
case "alert_type":
name = "alert.type";
break;
case "coldPath.maxDataSizeMB":
name = "coldPath_maxDataSizeMB";
break;
case "display.visualizations.charting.chart":
name += ".Type";
break;
case "homePath.maxDataSizeMB":
name = "homePath_maxDataSizeMB";
break;
case "update.checksum.type":
name = "update.checksum_type";
break;
}
}
string[] names = name.Split(':', '.');
var dictionary = value;
string propertyName;
dynamic propertyValue;
for (int i = 0; i < names.Length - 1; i++)
{
propertyName = NormalizePropertyName(names[i]);
if (dictionary.TryGetValue(propertyName, out propertyValue))
{
if (!(propertyValue is ExpandoObject))
{
throw new InvalidDataException(); // TODO: Diagnostics : conversion error
}
}
else
{
propertyValue = new ExpandoObject();
dictionary.Add(propertyName, propertyValue);
}
dictionary = (IDictionary<string, object>)propertyValue;
}
propertyName = NormalizePropertyName(names[names.Length - 1]);
propertyValue = await ParsePropertyValueAsync(reader, level + 1);
dictionary.Add(propertyName, propertyValue);
}
reader.EnsureMarkup(XmlNodeType.EndElement, "s:dict");
}
await reader.ReadAsync();
return value; // TODO: what's the type seen by dynamic?
}
示例9: ReadXmlAsync
/// <summary>
/// Asynchronously reads XML data into the current <see cref="AtomFeed"/>.
/// </summary>
/// <exception cref="InvalidDataException">
/// Thrown when an Invalid Data error condition occurs.
/// </exception>
/// <param name="reader">
/// The reader from which to read.
/// </param>
/// <returns>
/// A <see cref="Task"/> representing the operation.
/// </returns>
public async Task ReadXmlAsync(XmlReader reader)
{
Contract.Requires<ArgumentNullException>(reader != null, "reader");
this.Author = null;
this.Entries = null;
this.GeneratorVersion = null;
this.Id = null;
this.Links = null;
this.Messages = null;
this.Pagination = Pagination.None;
this.Title = null;
this.Updated = DateTime.MinValue;
reader.Requires(await reader.MoveToDocumentElementAsync("feed"));
var documentElementName = reader.Name;
List<AtomEntry> entries = null;
Dictionary<string, Uri> links = null;
List<Message> messages = null;
await reader.ReadAsync();
while (reader.NodeType == XmlNodeType.Element)
{
string name = reader.Name;
switch (name)
{
case "title":
this.Title = await reader.ReadElementContentAsync(StringConverter.Instance);
break;
case "id":
this.Id = await reader.ReadElementContentAsync(UriConverter.Instance);
break;
case "author":
await reader.ReadAsync();
reader.EnsureMarkup(XmlNodeType.Element, "name");
this.Author = await reader.ReadElementContentAsync(StringConverter.Instance);
reader.EnsureMarkup(XmlNodeType.EndElement, "author");
await reader.ReadAsync();
break;
case "generator":
// string build = reader.GetRequiredAttribute("build"); // TODO: Incorporate build number? Build number sometimes adds a fifth digit.
string version = reader.GetRequiredAttribute("version");
this.GeneratorVersion = VersionConverter.Instance.Convert(string.Join(".", version));
await reader.ReadAsync();
break;
case "updated":
this.Updated = await reader.ReadElementContentAsync(DateTimeConverter.Instance);
break;
case "entry":
var entry = new AtomEntry();
if (entries == null)
{
entries = new List<AtomEntry>();
}
entries.Add(entry);
await entry.ReadXmlAsync(reader);
break;
case "link":
var href = reader.GetRequiredAttribute("href");
var rel = reader.GetRequiredAttribute("rel");
if (links == null)
{
links = new Dictionary<string, Uri>();
}
links[rel] = UriConverter.Instance.Convert(href);
await reader.ReadAsync();
break;
//.........这里部分代码省略.........
示例10: ReadNavigationHeadAsync
private static async Task<EpubNavigationHead> ReadNavigationHeadAsync(XmlReader reader)
{
EpubNavigationHead result = new EpubNavigationHead();
//"ncx:head" is our starting point
bool headFound = await reader.ReadToFollowingAsync("head", "http://www.daisy.org/z3986/2005/ncx/");
if (!headFound)
throw new Exception("EPUB parsing error: head section not found in the .toc file.");
while (await reader.ReadAsync() && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "head"))
{
if (reader.LocalName.ToLowerInvariant() == "meta")
{
EpubNavigationHeadMeta meta = new EpubNavigationHeadMeta();
while (reader.MoveToNextAttribute())
{
switch (reader.LocalName.ToLowerInvariant())
{
case "name":
meta.Name = reader.Value;
break;
case "content":
meta.Content = reader.Value;
break;
case "scheme":
meta.Scheme = reader.Value;
break;
}
}
if (String.IsNullOrWhiteSpace(meta.Name))
throw new Exception("Incorrect EPUB navigation meta: meta name is missing");
if (meta.Content == null)
throw new Exception("Incorrect EPUB navigation meta: meta content is missing");
result.Add(meta);
}
}
return result;
}
示例11: ReadNavigationDocTitleAsync
private static async Task<EpubNavigationDocTitle> ReadNavigationDocTitleAsync(XmlReader reader)
{
EpubNavigationDocTitle result = new EpubNavigationDocTitle();
bool titleFound = await reader.ReadToFollowingAsync("docTitle", "http://www.daisy.org/z3986/2005/ncx/");
if (!titleFound)
throw new Exception("EPUB parsing error: title section not found in the .toc file.");
while (await reader.ReadAsync() && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "docTitle"))
{
if (reader.LocalName.ToLowerInvariant() == "text")
{
result.Add(reader.ReadElementContentAsString());
}
}
return result;
}
示例12: ReadNavigationAuthorsAsync
private static async Task<List<EpubNavigationDocAuthor>> ReadNavigationAuthorsAsync(XmlReader reader)
{
List<EpubNavigationDocAuthor> result = new List<EpubNavigationDocAuthor>();
bool authorFound = await reader.ReadToFollowingAsync("docAuthor", "http://www.daisy.org/z3986/2005/ncx/");
////we don't really care if there is no authors mentioned in toc file... But we could save a warning to a log file if any
//TO-DO: This code is very week as I don`t have any reliable tools to extract all of docAuthor nodes and parse them.
//So I`m relying on basic EPUB structure that demands that file should have at least one navMap node and all docAuthors should come before it
//I think I should rewrite this code later using LINQ to XML
while (await reader.ReadAsync() && !(reader.IsStartElement() && reader.LocalName == "navMap"))
{
EpubNavigationDocAuthor author = new EpubNavigationDocAuthor();
if (reader.NodeType == XmlNodeType.Text)
{
author.Add(reader.Value);
result.Add(author);
}
}
return result;
}
示例13: ReadNavigationLabelAsync
private static async Task<EpubNavigationLabel> ReadNavigationLabelAsync(XmlReader reader)
{
EpubNavigationLabel result = new EpubNavigationLabel();
var navigationLabelText = string.Empty;
//We have to read to <text> subnode of the navLabel node
do
{
if ((reader.LocalName.ToLowerInvariant() == "text") && (reader.NodeType == XmlNodeType.Element))
{
navigationLabelText = reader.ReadElementContentAsString();
}
} while (await reader.ReadAsync() && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName.ToLowerInvariant() == "navlabel"));
if (string.IsNullOrEmpty(navigationLabelText))
throw new Exception("Incorrect EPUB navigation label: label text element is missing");
result.Text = navigationLabelText;
return result;
}
示例14: ReadNavigationPointAsync
private static async Task<EpubNavigationPoint> ReadNavigationPointAsync(XmlReader reader)
{
EpubNavigationPoint result = new EpubNavigationPoint();
//we have to skip first entry as it could be empty after new sub-reader created
if (reader.NodeType == XmlNodeType.None) await reader.ReadAsync();
//Now the pointer should point to the <navPoint> itself
while (reader.MoveToNextAttribute()) //Doing this we just passing through <navPoint> tag
{
switch (reader.LocalName.ToLowerInvariant()) //We have to collect all possible attributes from the <navPoint>
{
case "id":
result.Id = reader.Value;
break;
case "class":
result.Class = reader.Value;
break;
case "playorder":
result.PlayOrder = reader.Value;
break;
}
}
if (String.IsNullOrWhiteSpace(result.Id))
throw new Exception("Incorrect EPUB navigation point: point ID is missing");
result.NavigationLabels = new List<EpubNavigationLabel>();
result.ChildNavigationPoints = new List<EpubNavigationPoint>();
// We need to make sure that we will return pointer back to <navPoint> entry after reading all attributes
reader.MoveToElement();
//Now we are looking for subnodes - navLabel, content and sub-navPoints
while (await reader.ReadAsync())
{
if (reader.NodeType != XmlNodeType.EndElement)
switch (reader.LocalName.ToLowerInvariant())
{
case "navlabel":
EpubNavigationLabel navigationLabel = await ReadNavigationLabelAsync(reader);// Adding label to collection
result.NavigationLabels.Add(navigationLabel);
break;
case "content":
EpubNavigationContent content = await ReadNavigationContentAsync(reader); //Adding content to collection
result.Content = content;
break;
case "navpoint": //Yeep. Looks like we found a <navPoint> sub-node
XmlReader subTree = reader.ReadSubtree(); //Cooking a separate sub-reader scope for this node to separate it from the others siblings
EpubNavigationPoint childNavigationPoint = await ReadNavigationPointAsync(subTree);// I hate recursion...
//Adding a child to a collection
result.ChildNavigationPoints.Add(childNavigationPoint);
subTree.Dispose();
break;
}
};
return result;
}
示例15: ReadXmlAsync
/// <summary>
/// Asynchronously reads data into the current <see cref="SearchPreview"/>.
/// </summary>
/// <param name="reader">
/// The <see cref="XmlReader"/> from which to read.
/// </param>
/// <returns>
/// A <see cref="Task"/> representing the operation.
/// </returns>
public async Task ReadXmlAsync(XmlReader reader)
{
Contract.Requires<ArgumentNullException>(reader != null);
//// Intitialize data members
this.metadata = new SearchResultMetadata();
await metadata.ReadXmlAsync(reader);
var results = new List<SearchResult>();
this.Results = new ReadOnlyCollection<SearchResult>(results);
//// Read the search preview
while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name == "results"))
{
var result = new SearchResult(this.metadata);
await result.ReadXmlAsync(reader);
results.Add(result);
await reader.ReadAsync();
}
}