本文整理汇总了C#中System.Xml.XmlTextReader.ReadToDescendant方法的典型用法代码示例。如果您正苦于以下问题:C# XmlTextReader.ReadToDescendant方法的具体用法?C# XmlTextReader.ReadToDescendant怎么用?C# XmlTextReader.ReadToDescendant使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Xml.XmlTextReader
的用法示例。
在下文中一共展示了XmlTextReader.ReadToDescendant方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParseCML
public static Molecule ParseCML(FileStream file)
{
Dictionary<int, BondingAtom> atoms = new Dictionary<int, BondingAtom>();
XmlTextReader reader = new XmlTextReader(file);
reader.ReadToFollowing("molecule");
reader.ReadToDescendant("atomArray");
reader.ReadToDescendant("atom");
do
{
atoms.Add(int.Parse(reader.GetAttribute("id").Substring(1)) - 1, new BondingAtom(Elements.FromSymbol(reader.GetAttribute("elementType"))));
} while (reader.ReadToNextSibling("atom"));
reader.ReadToNextSibling("bondArray");
reader.ReadToDescendant("bond");
do
{
string[] atomRefs = reader.GetAttribute("atomRefs2").Split(' ');
int order = 0;
switch (reader.GetAttribute("order"))
{
case "S":
order = 1;
break;
case "D":
order = 2;
break;
case "T":
order = 3;
break;
}
atoms[int.Parse(atomRefs[0].Substring(1)) - 1].Bond(atoms[int.Parse(atomRefs[1].Substring(1)) - 1], order);
} while (reader.ReadToNextSibling("bond"));
return new Molecule(new List<BondingAtom>(atoms.Values));
}
示例2: ReadXml
public static LocalizationData ReadXml(XmlTextReader xr)
{
Dictionary<String, Field[]> res = new Dictionary<string, Field[]>();
if (xr.ReadToDescendant("localization"))
if (xr.ReadToDescendant("type"))
do
{
List<Field> fields = new List<Field>();
var name = xr.GetAttribute("name");
if (xr.ReadToDescendant("field"))
do
{
switch (xr.NodeType)
{
case XmlNodeType.Element:
if (xr.Name == "field")
fields.Add(new Field { FieldName = xr.GetAttribute("name"), LocalizedText = xr.ReadElementContentAsString() });
break;
}
} while (xr.ReadToNextSibling("field"));
if (fields.Count > 0)
res[name] = fields.ToArray();
}
while (xr.ReadToNextSibling("type"));
return new LocalizationData(res);
}
示例3: GetXMLValue
public string GetXMLValue(XmlTextReader reader, String nodeName)
{
if (reader.ReadToDescendant(nodeName))
return reader.ReadElementContentAsString();
else
return "";
}
示例4: TryExtractImageUri
private static bool TryExtractImageUri(string fragment, out Uri imageUri)
{
try
{
XmlReader rdr = new XmlTextReader(fragment, XmlNodeType.Element, null);
rdr.Read();
if (rdr.Name != "img")
{
if (!rdr.ReadToDescendant("img"))
{
imageUri = null;
return false;
}
}
string attribute = rdr.GetAttribute("src");
if (!string.IsNullOrEmpty(attribute))
{
imageUri = new Uri(attribute);
return true;
}
else
{
imageUri = default(Uri);
return false;
}
}
catch (Exception ex)
{
imageUri = default(Uri);
return false;
}
}
示例5: PhotosSerializationSkipBlankPhotoRowTest
public void PhotosSerializationSkipBlankPhotoRowTest()
{
const string xml = @"<photos page=""1"" pages=""1"" perpage=""500"" total=""500"">
<photo id=""3662960087"" owner=""[email protected]"" secret=""9f8fcf9269"" server=""3379"" farm=""4"" title=""gecko closeup""
ispublic=""1"" isfriend=""0"" isfamily=""0"" dateupload=""1246050291""
tags=""reptile jinaacom geckocloseup geckoanatomy jinaajinahibrahim"" latitude=""1.45"" />
<photo id="""" owner="""" secret="""" server="""" farm=""0"" title=""""
ispublic="""" isfriend="""" isfamily="""" dateupload="""" tags="""" latitude="""" />
<photo id=""3662960087"" owner=""[email protected]"" secret=""9f8fcf9269"" server=""3379"" farm=""4"" title=""gecko closeup""
ispublic=""1"" isfriend=""0"" isfamily=""0"" dateupload=""1246050291"" tags=""reptile jinaacom geckocloseup geckoanatomy jinaajinahibrahim"" latitude=""1.45"" />
</photos>";
var photos = new PhotoCollection();
var sr = new StringReader(xml);
var reader = new XmlTextReader(sr) {WhitespaceHandling = WhitespaceHandling.Significant};
reader.ReadToDescendant("photos");
((IFlickrParsable) photos).Load(reader);
Assert.IsNotNull(photos, "Photos should not be null");
Assert.AreEqual(500, photos.Total, "Total photos should be 500");
Assert.AreEqual(2, photos.Count, "Should only contain 2 photo");
}
示例6: ProcessFile
public override void ProcessFile(string filePath, Dictionary<string, LocalizableEntity> map)
{
Logger.LogFormat("Processing file {0}", filePath);
XmlTextReader xr = new XmlTextReader(filePath);
string propertyPath = string.Empty;
try
{
if (xr.ReadToDescendant("localization"))
if (xr.ReadToDescendant("type"))
do
{
var className = xr.GetAttribute("name");
if (xr.ReadToDescendant("field"))
do
{
switch (xr.NodeType)
{
case XmlNodeType.Element:
if (xr.Name == "field")
{
String fieldName = xr.GetAttribute("name");
String fieldValue = xr.ReadElementContentAsString();
LocalizableEntity property = GetLocalizableProperty(filePath, className, fieldName, fieldValue);
propertyPath = property.FullEntityPath;
map.Add(propertyPath, property);
}
break;
}
} while (xr.ReadToNextSibling("field"));
} while (xr.ReadToNextSibling("type"));
}
catch (Exception ex)
{
Logger.LogFormat("Error ({0})", filePath);
throw new ExtractorException("Error: '{0}'. Property path: '{1}'", ex.Message, propertyPath);
}
finally
{
xr.Close();
}
}
示例7: OrderWizard
static OrderWizard()
{
string conditionsDataPath =
HttpContext.Current.Server.MapPath(PathToJoesPubSeatingConditions);
XmlTextReader reader = new XmlTextReader(conditionsDataPath);
if (!reader.ReadToFollowing("pubSeatingConditions"))
throw new XmlException("Can't find <pubSeatingConditions> node.");
if (!reader.ReadToDescendant("section"))
throw new XmlException("Can't find any <section> nodes.");
syosSeatingConditions = new Dictionary<int, string>();
do
{
if (!reader.MoveToAttribute("id"))
throw new XmlException("Can't find \"id\" attribute for <section>.");
int id = Int32.Parse(reader.Value.Trim());
reader.MoveToElement();
string conditions = reader.ReadElementContentAsString();
syosSeatingConditions.Add(id, conditions);
}
while (reader.ReadToNextSibling("section"));
}
示例8: IsResgenRequired
// true if the resx file or any file referenced
// by the resx is newer than the .resources file
public static bool IsResgenRequired (string resx_filename)
{
if (String.Compare (Path.GetExtension (resx_filename), ".resx", true) != 0)
throw new ArgumentException (".resx file expected", "resx_filename");
string resources_filename = Path.ChangeExtension (resx_filename, ".resources");
if (IsFileNewerThan (resx_filename, resources_filename))
return true;
XmlTextReader xr = null;
try {
// look for
// <data type="System.Resources.ResXFileRef, System.Windows.Forms" ..>
// <value>... filename;.. </value>
// </data>
xr = new XmlTextReader (resx_filename);
string basepath = Path.GetDirectoryName (resx_filename);
while (xr.Read ()) {
if (xr.NodeType != XmlNodeType.Element ||
String.Compare (xr.LocalName, "data") != 0)
continue;
string type = xr.GetAttribute ("type");
if (String.IsNullOrEmpty (type))
continue;
if (String.Compare (type, "System.Resources.ResXFileRef, System.Windows.Forms") != 0)
continue;
xr.ReadToDescendant ("value");
if (xr.NodeType != XmlNodeType.Element)
continue;
string value = xr.ReadElementContentAsString ();
string [] parts = value.Split (';');
if (parts.Length > 0) {
string referenced_filename = MSBuildProjectService.FromMSBuildPath (
String.Empty, Path.Combine (basepath, parts [0]).Trim ());
if (File.Exists (referenced_filename) &&
IsFileNewerThan (referenced_filename, resources_filename))
return true;
}
}
} catch (XmlException) {
// Ignore xml errors, let resgen handle it
return true;
} finally {
if (xr != null)
xr.Close ();
}
return false;
}
示例9: ReturnGitHubContentFiles
//This returns all Files that are included in the plugin folder from GitHub.
internal static List<string> ReturnGitHubContentFiles()
{
List<string> returnValues = new List<string>();
try
{
using (XmlTextReader reader = new XmlTextReader(GitHubProjectUrl))
{
// simply (and easily) skip the junk at the beginning
reader.MoveToContent();
reader.ReadToDescendant("ItemGroup");
if ((reader.NodeType == XmlNodeType.Element) &&
(reader.Name == "ItemGroup"))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) &&
(reader.IsStartElement()) &&
reader.HasAttributes)
{
switch (reader.LocalName)
{
case "Content":
case "None":
case "Compile":
string s = reader.GetAttribute(0);
returnValues.Add(s);
break;
}
}
}
}
}
}
catch (Exception)
{
}
return returnValues;
}
示例10: Deserialize
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void Deserialize(string data) {
// If there is nothing to deserialize, return a newly created instance of the target type.
if (String.IsNullOrEmpty(data))
return;
// Decompress and deserialize the data.
byte[] decoded_buffer = Convert.FromBase64String(data);
using (var zipped = new MemoryStream(decoded_buffer)) {
using (var s = new GZipStream(zipped, CompressionMode.Decompress)) {
using (var reader = new XmlTextReader(s)) {
if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "configuration") {
if (reader.ReadToDescendant("entry")) {
var depth = reader.Depth;
ReadEntryFromXml(reader);
var shouldContinue = true;
while (shouldContinue && reader.Depth == depth)
shouldContinue = ReadEntryFromXml(reader);
}
reader.Read();
}
}
}
}
}
示例11: Import
public bool Import(string fileName, bool deleteBeforeImport, bool showProgress)
{
//System.Diagnostics.Debugger.Launch();
_errorMessage = "";
if (_isImporting == true)
{
_errorMessage = "already importing...";
return false;
}
_isImporting = true;
bool result = false;
XmlTextReader xmlReader = null;
// remove old programs
_status.Status = "Removing old programs";
_status.Channels = 0;
_status.Programs = 0;
_status.StartTime = DateTime.Now;
_status.EndTime = new DateTime(1971, 11, 6);
if (showProgress && ShowProgress != null) ShowProgress(_status);
layer.RemoveOldPrograms();
/*
// for each channel, get the last program's time
Dictionary<int, DateTime> lastProgramForChannel = new Dictionary<int, DateTime>();
IList channels = Channel.ListAll();
foreach (Channel ch in channels)
{
SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(TvDatabase.Program));
sb.AddConstraint(Operator.Equals, "idChannel", ch.IdChannel);
sb.AddOrderByField(false, "starttime");
sb.SetRowLimit(1);
SqlStatement stmt = sb.GetStatement(true);
IList programsInDbs = ObjectFactory.GetCollection(typeof(TvDatabase.Program), stmt.Execute());
DateTime lastProgram = DateTime.MinValue;
if (programsInDbs.Count > 0)
{
TvDatabase.IProgram p = (TvDatabase.Program)programsInDbs[0];
lastProgram = p.EndTime;
}
lastProgramForChannel[ch.IdChannel] = lastProgram;
}*/
//TVDatabase.SupressEvents = true;
bool useTimeZone = layer.GetSetting("xmlTvUseTimeZone", "false").Value == "true";
int hours = Int32.Parse(layer.GetSetting("xmlTvTimeZoneHours", "0").Value);
int mins = Int32.Parse(layer.GetSetting("xmlTvTimeZoneMins", "0").Value);
int timeZoneCorrection = hours * 60 + mins;
ArrayList Programs = new ArrayList();
Dictionary<int, ChannelPrograms> dChannelPrograms = new Dictionary<int, ChannelPrograms>();
try
{
Log.WriteFile("xmltv import {0}", fileName);
//
// Make sure the file exists before we try to do any processing
//
if (File.Exists(fileName))
{
_status.Status = "Loading channel list";
_status.Channels = 0;
_status.Programs = 0;
_status.StartTime = DateTime.Now;
_status.EndTime = new DateTime(1971, 11, 6);
if (showProgress && ShowProgress != null) ShowProgress(_status);
Dictionary<int, Channel> guideChannels = new Dictionary<int, Channel>();
IList<Channel> allChannels = Channel.ListAll();
int iChannel = 0;
xmlReader = new XmlTextReader(fileName);
#region import non-mapped channels by their display-name
if (xmlReader.ReadToDescendant("tv"))
{
// get the first channel
if (xmlReader.ReadToDescendant("channel"))
{
do
{
String id = xmlReader.GetAttribute("id");
if (id == null || id.Length == 0)
{
Log.Error(" channel#{0} doesnt contain an id", iChannel);
}
else
{
String displayName = null;
XmlReader xmlChannel = xmlReader.ReadSubtree();
xmlChannel.ReadStartElement(); // read channel
// now, xmlChannel is positioned on the first sub-element of <channel>
//.........这里部分代码省略.........
示例12: GetConfigFileFromAppConfig
/// <summary>
/// Gets the config file location from app config.
/// </summary>
private string GetConfigFileFromAppConfig(FileInfo appConfigFile)
{
try
{
XmlTextReader reader = new XmlTextReader(appConfigFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
try
{
reader.MoveToContent();
if (reader.ReadToDescendant("ConfigurationLocation", Namespaces.OpcUaConfig))
{
if (reader.ReadToDescendant("FilePath", Namespaces.OpcUaConfig))
{
reader.MoveToContent();
return reader.ReadInnerXml();
}
}
return null;
}
finally
{
reader.Close();
}
}
catch (Exception)
{
return null;
}
}
示例13: DeserializeNetwork
internal void DeserializeNetwork(string filePath)
{
var tempNodeCollection = new List<Node>();
NewFile();
// Create an reader
using (var reader = new XmlTextReader(filePath))
{
reader.MoveToContent();
var enumString = reader.GetAttribute("GraphFlowDirection");
if (enumString != null)
{
ImportFlowDirection =
(GraphFlowDirections) Enum.Parse(typeof (GraphFlowDirections), enumString, true);
}
reader.ReadToDescendant("Nodes");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name != null)
{
var type = Type.GetType(reader.Name);
if (type == null)
{
try // try to find type in entry assembly
{
var assembly = Assembly.GetEntryAssembly();
type = assembly.GetTypes().FirstOrDefault(t => t.FullName == reader.Name);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
try // try to find type in ExternalNodeTypes
{
type = ExternalNodeTypes.ToArray()
.FirstOrDefault(t => t.FullName == reader.Name);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
if (type != null)
{
if (type.IsSubclassOf(typeof (Node)))
{
var node = (Node) Activator.CreateInstance(type, this);
node.DeserializeNetwork(reader);
tempNodeCollection.Add(node);
}
else if (type == typeof (Connector))
{
Node startNode = null;
Node endNode = null;
var value = reader.GetAttribute("StartNode");
if (value != null)
{
startNode =
NodeCollection.FirstOrDefault(node => node.Guid == new Guid(value));
}
value = reader.GetAttribute("EndNode");
if (value != null)
endNode = NodeCollection.FirstOrDefault(node => node.Guid == new Guid(value));
value = reader.GetAttribute("StartIndex");
var startIndex = Convert.ToInt32(value);
value = reader.GetAttribute("EndIndex");
var endIndex = Convert.ToInt32(value);
if (startNode != null && endNode != null)
{
var startPort = startNode.OutputPorts[startIndex];
var endPort = endNode.InputPorts[endIndex];
if (startPort != null && endPort != null)
{
var connector = new Connector(this, startPort, endPort);
ConnectorCollection.Add(connector);
}
}
}
//.........这里部分代码省略.........
示例14: LoadPersonalizationState
public override PersonalizationState LoadPersonalizationState(WebPartManager webPartManager, bool ignoreCurrentUser)
{
if (null == webPartManager) throw new ArgumentNullException("webPartManager is null");
DictionaryPersonalizationState state = new DictionaryPersonalizationState(webPartManager);
string suid = this.GetScreenUniqueIdentifier();
Cache cache = HttpRuntime.Cache;
lock (SyncRoot)
{
Dictionary<string, PersonalizationDictionary> cachedstates = cache[suid] as Dictionary<string, PersonalizationDictionary>;
if ((this.IsEnabled && !state.ReadOnly) || null == cachedstates)
{
string storage = PersonalizationStorage.Instance.Read(XmlPersonalizationProvider.StorageKey, XmlPersonalizationProvider.StorageTemplate);
if (!string.IsNullOrEmpty(storage))
{
using (XmlTextReader reader = new XmlTextReader(new StringReader(storage)))
{
reader.MoveToContent();
if (reader.MoveToAttribute("readOnly"))
{
bool isReadOnly = false;
bool.TryParse(reader.Value, out isReadOnly);
state.ReadOnly = isReadOnly;
reader.MoveToElement();
}
if (reader.ReadToDescendant("part"))
{
int partDepth = reader.Depth;
do
{
reader.MoveToElement();
reader.MoveToAttribute("id");
string id = reader.Value;
PersonalizationDictionary dictionary = new PersonalizationDictionary();
reader.MoveToContent();
if (reader.ReadToDescendant("property"))
{
int propertyDepth = reader.Depth;
do
{
reader.MoveToElement();
reader.MoveToAttribute("name");
string name = reader.Value;
reader.MoveToAttribute("sensitive");
bool sensitive = bool.Parse(reader.Value);
reader.MoveToAttribute("scope");
PersonalizationScope scope = (PersonalizationScope)int.Parse(reader.Value);
object value = null;
reader.MoveToContent();
if (reader.ReadToDescendant("value"))
{
reader.MoveToAttribute("type");
if (reader.HasValue)
{
Type type = Type.GetType(reader.Value);
if (type == null && name == "Configuration")
{
type = Type.GetType("LWAS.Infrastructure.Configuration.Configuration, LWAS");
}
reader.MoveToContent();
value = SerializationServices.Deserialize(type, reader);
}
}
dictionary.Add(name, new PersonalizationEntry(value, scope, sensitive));
reader.MoveToElement();
while (propertyDepth < reader.Depth && reader.Read())
{
}
}
while (reader.ReadToNextSibling("property"));
}
state.States.Add(id, dictionary);
reader.MoveToElement();
while (partDepth < reader.Depth && reader.Read())
{
}
}
while (reader.ReadToNextSibling("part"));
}
}
}
string fileToMonitor = PersonalizationStorage.Instance.BuildPath(StorageKey);
if (!PersonalizationStorage.Instance.Agent.HasKey(fileToMonitor))
fileToMonitor = PersonalizationStorage.Instance.BuildPath(StorageTemplate);
cache.Insert(suid, state.States, new CacheDependency(HttpContext.Current.Server.MapPath(fileToMonitor)));
}
else
state.States = cachedstates;
}
return state;
}
示例15: decryptToken
/// <summary>
/// Decrpyts a security token from an XML EncryptedData
/// </summary>
/// <param name="xmlToken">the XML token to decrypt</param>
/// <returns>A byte array of the contents of the encrypted token</returns>
private static byte[] decryptToken(string xmlToken)
{
int encryptionAlgorithm;
int m_keyEncryptionAlgorithm;
string m_keyHashAlgorithm;
byte[] thumbprint;
byte[] securityTokenData;
byte[] symmetricKeyData;
XmlReader reader = new XmlTextReader(new StringReader(xmlToken));
// Find the EncryptionMethod element, grab the Algorithm
if (!reader.ReadToDescendant(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace))
throw new ArgumentException("Cannot find token EncryptedMethod.");
encryptionAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm).GetHashCode();
// Find the EncryptionMethod element for the key, grab the Algorithm
if (!reader.ReadToFollowing(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace))
throw new ArgumentException("Cannot find key EncryptedMethod.");
m_keyEncryptionAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm).GetHashCode();
// Find the Digest method for the key identifier
if (!reader.ReadToFollowing(XmlSignatureStrings.DigestMethod, XmlSignatureStrings.Namespace))
throw new ArgumentException("Cannot find Digest Method.");
m_keyHashAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm);
// Find the key identifier
if (!reader.ReadToFollowing(WSSecurityStrings.KeyIdentifier, WSSecurityStrings.Namespace))
throw new ArgumentException("Cannot find Key Identifier.");
reader.Read();
thumbprint = Convert.FromBase64String(reader.ReadContentAsString());
// Find the encrypted Symmetric Key
if (!reader.ReadToFollowing(XmlEncryptionStrings.CipherValue, XmlEncryptionStrings.Namespace))
throw new ArgumentException("Cannot find symmetric key.");
reader.Read();
symmetricKeyData = Convert.FromBase64String(reader.ReadContentAsString());
// Find the encrypted Security Token
if (!reader.ReadToFollowing(XmlEncryptionStrings.CipherValue, XmlEncryptionStrings.Namespace))
throw new ArgumentException("Cannot find encrypted security token.");
reader.Read();
securityTokenData = Convert.FromBase64String(reader.ReadContentAsString());
reader.Close();
SymmetricAlgorithm alg = null;
X509Certificate2 certificate = FindCertificate(thumbprint);
foreach (int i in Aes)
if (encryptionAlgorithm == i)
{
alg = new RijndaelManaged();
break;
}
if (null == alg)
foreach (int i in TripleDes)
if (encryptionAlgorithm == i)
{
alg = new TripleDESCryptoServiceProvider();
break;
}
if (null == alg)
throw new ArgumentException("Could not determine Symmetric Algorithm");
alg.Key = (certificate.PrivateKey as RSACryptoServiceProvider).Decrypt(symmetricKeyData, true); ;
int ivSize = alg.BlockSize / 8;
byte[] iv = new byte[ivSize];
Buffer.BlockCopy(securityTokenData, 0, iv, 0, iv.Length);
alg.Padding = PaddingMode.ISO10126;
alg.Mode = CipherMode.CBC;
ICryptoTransform decrTransform = alg.CreateDecryptor(alg.Key, iv);
byte[] plainText = decrTransform.TransformFinalBlock(securityTokenData, iv.Length, securityTokenData.Length - iv.Length);
decrTransform.Dispose();
return plainText;
}