public static void Load( XmlElement xml ) { DisableAll(); if ( xml == null ) return; foreach( XmlElement el in xml.GetElementsByTagName( "filter" ) ) { try { LocString name = (LocString)Convert.ToInt32( el.GetAttribute( "name" ) ); string enable = el.GetAttribute( "enable" ); for(int i=0;i<m_Filters.Count;i++) { Filter f = (Filter)m_Filters[i]; if ( f.Name == name ) { if ( Convert.ToBoolean( enable ) ) f.OnEnable(); break; } } } catch { } } }
public CitySpawnList(string type, XmlElement xml) { m_Type = type; foreach (XmlElement element in xml.GetElementsByTagName("minions")) { foreach (XmlElement obj in element.GetElementsByTagName("object")) { Type mobile = null; if (!Region.ReadType(obj, "type", ref mobile)){ } m_Minions.Add(mobile); } } foreach (XmlElement element in xml.GetElementsByTagName("captains")) { foreach (XmlElement obj in element.GetElementsByTagName("object")) { Type mobile = null; if (!Region.ReadType(obj, "type", ref mobile)){ } m_Captains.Add(mobile); } } foreach (XmlElement element in xml.GetElementsByTagName("general")) { foreach (XmlElement obj in element.GetElementsByTagName("object")) { Type mobile = null; if (!Region.ReadType(obj, "type", ref mobile)){ } m_General.Add(mobile); } } }
public void Configure(XmlElement configurationElement) { var validatorEl = configurationElement.GetElementsByTagName("validator") .OfType<XmlElement>().FirstOrDefault(x => x.HasAttribute("type")); if (validatorEl == null) { throw new ConfigurationErrorsException("Missing required validator element for Basic Authentication authentication provider."); } var validatorType = Type.GetType(validatorEl.GetAttribute("type")); if (validatorType == null) { throw new ConfigurationErrorsException(String.Format("Cannot resolve validator type '{0}'", validatorEl.GetAttribute("type"))); } var userValidator = Activator.CreateInstance(validatorType) as IUserValidator; if (userValidator == null) { throw new ConfigurationErrorsException(String.Format("Type {0} does not implement the IUserValidator interface.", validatorType.FullName)); } if (userValidator is IConfigurableUserValidator) { (userValidator as IConfigurableUserValidator).Configure(validatorEl); } var realmEl = configurationElement.GetElementsByTagName("realm").OfType<XmlElement>().FirstOrDefault(); var realm = realmEl == null ? "BrightstarDB" : realmEl.InnerText; _configuration= new BasicAuthenticationConfiguration(userValidator, realm); }
private Bin GetBin(XmlElement xmlElement, string prefix) { XmlNodeList xmlNodeList = xmlElement.GetElementsByTagName(prefix + "Value"); int binValue = -1; if ((xmlNodeList.Count == 1) && (xmlNodeList.Item(0) is XmlElement)) binValue = Convert.ToInt32((xmlNodeList.Item(0) as XmlElement).InnerText); xmlNodeList = xmlElement.GetElementsByTagName(prefix + "Good"); bool isGoodDie = false; if ((xmlNodeList.Count == 1) && (xmlNodeList.Item(0) is XmlElement)) isGoodDie = Convert.ToBoolean((xmlNodeList.Item(0) as XmlElement).InnerText); xmlNodeList = xmlElement.GetElementsByTagName(prefix + "Reprobed"); bool isReprobedDie = false; if ((xmlNodeList.Count == 1) && (xmlNodeList.Item(0) is XmlElement)) isReprobedDie = Convert.ToBoolean((xmlNodeList.Item(0) as XmlElement).InnerText); xmlNodeList = xmlElement.GetElementsByTagName(prefix + "Inked"); bool isInkedDie = false; if ((xmlNodeList.Count == 1) && (xmlNodeList.Item(0) is XmlElement)) isInkedDie = Convert.ToBoolean((xmlNodeList.Item(0) as XmlElement).InnerText); if ((binValue >= 0) && (binValue < 256)) return new Bin(binValue, isGoodDie, isReprobedDie, isInkedDie); return null; }
private void BuildGroupFromXML(XmlElement xmlElement) { try { this.GroupEvaluationType = (GroupEvalType)Enum.Parse(typeof(GroupEvalType), xmlElement.GetAttribute("Evaluation")); // Group must have sub-groups and/or conditions Debug.Assert(xmlElement.HasChildNodes); // TODO: check names and get them from resource foreach (XmlNode condition_node in xmlElement.GetElementsByTagName("Condition")) { this.conditions.Add(new Condition(condition_node)); } foreach (XmlNode group_node in xmlElement.GetElementsByTagName("Group")) { this.sub_groups.Add(new ConditionGroup(group_node)); } } catch { // TODO } }
public RegistrationSummary(XmlElement reportElem) { this.Complete = reportElem.GetElementsByTagName("complete")[0].InnerText; this.Success = reportElem.GetElementsByTagName("success")[0].InnerText; this.TotalTime = reportElem.GetElementsByTagName("totaltime")[0].InnerText; this.Score = reportElem.GetElementsByTagName("score")[0].InnerText; }
public Entry(XmlElement element) { Id = Util.ChildValue(element, "id"); Title = Util.ChildValue(element, "title"); Link = Util.ChildValue(element, "link"); Published = DateTime.Parse(Util.ChildValue(element, "published")); Updated = DateTime.Parse(Util.ChildValue(element, "updated")); User = new User(Util.ChildElement(element, "user")); Service = new Service(Util.ChildElement(element, "service")); Comments = new CommentList(); foreach (XmlElement child in element.GetElementsByTagName("comment")) { Comments.Add(new Comment(child)); } Likes = new LikeList(); foreach (XmlElement child in element.GetElementsByTagName("like")) { Likes.Add(new Like(child)); } Media = new MediaList(); foreach (XmlElement child in element.GetElementsByTagName("media")) { Media.Add(new Media(child)); } }
public StatementData(XmlElement xml) { AccountNumber = FixmlUtil.ReadString(xml, "Acct"); XmlNodeList fundsXml = xml.GetElementsByTagName("Fund"); XmlNodeList positionsXml = xml.GetElementsByTagName("Position"); Funds = new Dictionary<StatementFundType, decimal>(fundsXml.Count); Positions = new Dictionary<FixmlInstrument, PosQuantity>(positionsXml.Count); foreach (XmlElement elem in fundsXml) { StatementFundType key; try { key = StatementFundUtil.Read(elem, "name"); } catch (FixmlException e) { e.PrintWarning(); continue; } decimal value = FixmlUtil.ReadDecimal(elem, "value"); Funds.Add(key, value); } foreach (XmlElement elem in positionsXml) { FixmlInstrument key = FixmlInstrument.FindById(FixmlUtil.ReadString(elem, "Isin")); int acc110 = FixmlUtil.ReadInt(elem, "Acc110"); int acc120 = FixmlUtil.ReadInt(elem, "Acc120", true) ?? 0; Positions.Add(key, new PosQuantity(acc110, acc120)); } // nie zaszkodzi się upewnić - czy to, co NOL3 podesłał, stanowi jakąś integralną całość... // (i czy ja w ogóle słusznie zakładam, jakie powinny być zależności między tymi wartościami) // - dla rachunku akcyjnego: if (CheckFundsSum(StatementFundType.CashReceivables, StatementFundType.Cash, StatementFundType.Receivables)) CheckFundsSum(StatementFundType.PortfolioValue, StatementFundType.CashReceivables, StatementFundType.SecuritiesValue); // - dla rachunku kontraktowego: if (CheckFundsSum(StatementFundType.Deposit, StatementFundType.DepositBlocked, StatementFundType.DepositFree)) CheckFundsSum(StatementFundType.PortfolioValue, StatementFundType.Cash, StatementFundType.CashBlocked, StatementFundType.Deposit); }
public static BackgroundItemStruct fromXML(XmlElement element) { BackgroundItemStruct str = new BackgroundItemStruct(); str.location = XMLUtil.fromXMLVector2(element.GetElementsByTagName("location")[0]); str.texturePath = element.GetElementsByTagName("path")[0].FirstChild.Value; str.rotation = element.GetAttribute("rotation") != "" ? float.Parse(element.GetAttribute("rotation")) : 0f; str.scale = element.GetAttribute("scale") == "" ? 1f : float.Parse(element.GetAttribute("scale")); return str; }
/// <summary> /// Inflate launch info object from passed in xml element /// </summary> /// <param name="launchInfoElem"></param> /// <param name="postbackInfoElem"></param> public PostbackInfo(XmlElement postbackInfoElem) { this.RegistrationId = postbackInfoElem.GetAttribute("regid"); this.Url = ((XmlElement)postbackInfoElem.GetElementsByTagName("url")[0]).InnerText; //this.Url = postbackInfoElem.GetAttribute("url"); this.LearnerLogin = ((XmlElement)postbackInfoElem.GetElementsByTagName("login")[0]).InnerText; this.LearnerPassword = ((XmlElement)postbackInfoElem.GetElementsByTagName("password")[0]).InnerText; this.RegistrationResultsAuthType = ((XmlElement)postbackInfoElem.GetElementsByTagName("authtype")[0]).InnerText; }
public void Read(XmlElement element) { this.Name = element.GetElementsByTagName("LevelName")[0].InnerText; this.Sprites.Clear(); foreach (XmlNode node in element.GetElementsByTagName("Sprites")[0].ChildNodes) { this.Sprites.Add(manager.SpriteManager.SpriteFromXML(node)); } }
private static ValidationRuleSet CompileRuleset(XmlElement rulesetNode) { var compiler = new XmlSpecificationCompiler(ScriptLanguage); var rules = CollectionUtils.Map<XmlElement, ISpecification>( rulesetNode.GetElementsByTagName(TagValidationRule), compiler.Compile); var applicabilityRuleNode = CollectionUtils.FirstElement(rulesetNode.GetElementsByTagName(TagApplicabililtyRule)); return applicabilityRuleNode != null ? new ValidationRuleSet(rules, compiler.Compile((XmlElement)applicabilityRuleNode)) : new ValidationRuleSet(rules); }
public void Read(XmlElement element) { XmlNode dims = element.GetElementsByTagName("Dims")[0]; XmlNode pos = element.GetElementsByTagName("Pos")[0]; XmlNode startPos = element.GetElementsByTagName("StartPos")[0]; this.TextureImage = Manager.contentManager.GetPlatformTexture(int.Parse(dims.ChildNodes[0].InnerText), int.Parse(dims.ChildNodes[1].InnerText), int.Parse(dims.ChildNodes[2].InnerText)); this.Position = new Vector2(float.Parse(pos.FirstChild.InnerText), float.Parse(pos.LastChild.InnerText)); this.StartPosition = new Vector2(float.Parse(startPos.FirstChild.InnerText), float.Parse(startPos.LastChild.InnerText)); this.FrameDims = new Point(this.TextureImage.Width, this.TextureImage.Height); }
/// <summary> /// Constructor which takes an XML node as returned by the web service. /// </summary> /// <param name="instanceElem"></param> public InstanceData(XmlElement instanceElem) { this.InstanceId = ((XmlElement)instanceElem .GetElementsByTagName("instanceId")[0]) .InnerText; this.CourseVersion = ((XmlElement)instanceElem .GetElementsByTagName("courseVersion")[0]) .InnerText; this.UpdateDate = DateTime.Parse(((XmlElement)instanceElem .GetElementsByTagName("updateDate")[0]) .InnerText); }
public void ReadFrom(XmlElement jobAndWorkerTypeElement) { //JobType Debug.Assert(jobAndWorkerTypeElement != null, "jobAndWorkerTypeElement != null"); var jobTypeElement = (XmlElement)jobAndWorkerTypeElement.GetElementsByTagName("JobType")[0]; JobType = new RuntimeType(); JobType.ReadFrom(jobTypeElement); //WorkerType var workerTypeElement = (XmlElement)jobAndWorkerTypeElement.GetElementsByTagName("WorkerType")[0]; WorkerType = new RuntimeType(); WorkerType.ReadFrom(workerTypeElement); }
//Construct Definition from a XML element containing the nessecary data public Definition(XmlElement Element) { this.Name = Element.GetElementsByTagName("Name")[0].InnerText; this.GroupName = Element.GetElementsByTagName("GroupName")[0].InnerText; this.Description = Element.GetElementsByTagName("Description")[0].InnerText; this.Active = (Element.GetElementsByTagName("Active")[0].InnerText == "1"); if (this.Active) { XmlElement ArgsElement = (XmlElement)Element.GetElementsByTagName("Args")[0]; if (ArgsElement.ChildNodes.Count > 0) { this.Args = new object[ArgsElement.GetElementsByTagName("Arg").Count]; int Count = 0; foreach (XmlElement ArgElement in ArgsElement.GetElementsByTagName("Arg")) { this.Args[Count] = Serializer.DeserializeXML((XmlElement)ArgsElement.FirstChild); } } } this.NeedsParams = (Element.GetElementsByTagName("NeedsParams")[0].InnerText == "1"); if (this.NeedsParams) { this.FormSource = new Source((XmlElement)Element.GetElementsByTagName("FormSource")[0]); } this.Source = new Source((XmlElement)Element.GetElementsByTagName("Source")[0]); }
/// <summary> /// Constructor which takes an XML node as returned by the web service. /// </summary> /// <param name="regDataEl"></param> public RegistrationData(XmlElement registrationElem) { this.RegistrationId = registrationElem.Attributes["id"].Value; this.CourseId = registrationElem.Attributes["courseid"].Value; this.CourseTitle = ((XmlElement)registrationElem .GetElementsByTagName("courseTitle")[0]) .InnerText; this.LastCourseVersionLaunched = ((XmlElement)registrationElem .GetElementsByTagName("lastCourseVersionLaunched")[0]) .InnerText; this.LearnerId = ((XmlElement)registrationElem .GetElementsByTagName("learnerId")[0]) .InnerText; this.LearnerFirstName = ((XmlElement)registrationElem .GetElementsByTagName("learnerFirstName")[0]) .InnerText; this.LearnerLastName = ((XmlElement)registrationElem .GetElementsByTagName("learnerLastName")[0]) .InnerText; this.Email = ((XmlElement)registrationElem .GetElementsByTagName("email")[0]) .InnerText; this.CreateDate = DateTime.Parse(((XmlElement)registrationElem .GetElementsByTagName("createDate")[0]) .InnerText); this.FirstAccessDate = Utils.ParseNullableDate(((XmlElement)registrationElem .GetElementsByTagName("firstAccessDate")[0]) .InnerText); this.LastAccessDate = Utils.ParseNullableDate(((XmlElement)registrationElem .GetElementsByTagName("lastAccessDate")[0]) .InnerText); this.CompletedDate = Utils.ParseNullableDate(((XmlElement)registrationElem .GetElementsByTagName("completedDate")[0]) .InnerText); this.Instances = InstanceData.ConvertToInstanceDataList((XmlElement)registrationElem.GetElementsByTagName("instances")[0]); }
public static XmlNode GetSubNode(XmlElement element, string fullNodeName) { XmlNodeList nodeList = element.GetElementsByTagName(fullNodeName); if (nodeList.Count != 1) return null; return nodeList[0]; }
private static PageCachePreloadConfiguration ProcessPreloadConfiguration(XmlElement preloadPages) { var enabled = IsEnabled(preloadPages); var preloadConfiguration = new PageCachePreloadConfiguration {Enabled = enabled}; decimal defaultRatio; preloadConfiguration.DefaultCacheRatio = Decimal.TryParse(preloadPages.GetAttribute("defaultCacheRatio"), out defaultRatio) ? defaultRatio : 1.0m; preloadConfiguration.StorePreloadConfigurations = new Dictionary<string, StorePreloadConfiguration>(); foreach (var storeConfiguration in preloadPages.GetElementsByTagName("store").OfType<XmlElement>()) { var storeName = storeConfiguration.GetAttribute("name"); decimal cacheRatio; if (!String.IsNullOrEmpty(storeName) && Decimal.TryParse(storeConfiguration.GetAttribute("cacheRatio"), out cacheRatio)) { preloadConfiguration.StorePreloadConfigurations[storeName] = new StorePreloadConfiguration { CacheRatio = cacheRatio }; } } return preloadConfiguration; }
private static IList<ArchivedChatId> GetChatIdsFromStanza(XmlElement xml) { List<ArchivedChatId> chats = new List<ArchivedChatId>(); var chatNodes = xml.GetElementsByTagName("chat"); foreach (XmlNode node in chatNodes) { string with = null; try { with = node.Attributes["with"].InnerText; } catch { } DateTimeOffset start = default(DateTimeOffset); try { string startText = node.Attributes["start"].InnerText; start = DateTimeProfiles.FromXmppString(startText); } catch { } chats.Add(new ArchivedChatId(with, start)); } return chats; }
/// <summary> /// Create a complexity regulation strategy based on the provided XML config values. /// </summary> public static IComplexityRegulationStrategy CreateComplexityRegulationStrategy(XmlElement xmlConfig, string complexityElemName) { // Get root activation element. XmlNodeList nodeList = xmlConfig.GetElementsByTagName(complexityElemName, ""); if (nodeList.Count != 1) { throw new ArgumentException("Missing or invalid complexity XML config setting."); } XmlElement xmlComplexity = nodeList[0] as XmlElement; string complexityRegulationStr = XmlUtils.TryGetValueAsString(xmlComplexity, "ComplexityRegulationStrategy"); int? complexityThreshold = XmlUtils.TryGetValueAsInt(xmlComplexity, "ComplexityThreshold"); ComplexityCeilingType ceilingType; if(!Enum.TryParse<ComplexityCeilingType>(complexityRegulationStr, out ceilingType)) { return new NullComplexityRegulationStrategy(); } if(null == complexityThreshold) { throw new ArgumentNullException("threshold", string.Format("threshold must be provided for complexity regulation strategy type [{0}]", ceilingType)); } return new DefaultComplexityRegulationStrategy(ceilingType, complexityThreshold.Value); }
protected VcConfigurationBase(XmlElement elem, ProjectBase parentProject, DirectoryInfo outputDir) : base(parentProject) { if (elem == null) { throw new ArgumentNullException("elem"); } // output directory override (if specified) _outputDir = outputDir; // get name of configuration (also contains the targeted platform) _name = elem.GetAttribute("Name"); XmlNodeList tools = elem.GetElementsByTagName("Tool"); foreach (XmlElement toolElem in tools) { string toolName = toolElem.GetAttribute("Name"); Hashtable htToolSettings = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach(XmlAttribute attr in toolElem.Attributes) { if (attr.Name != "Name") { htToolSettings[attr.Name] = attr.Value; } } Tools[toolName] = htToolSettings; } }
/// <summary> Populates a Composite type by looping through it's children, finding corresponding /// Elements among the children of the given Element, and calling parse(Type, Element) for /// each. /// </summary> private void parseComposite(Composite datatypeObject, System.Xml.XmlElement datatypeElement) { if (datatypeObject is GenericComposite) { //elements won't be named GenericComposite.x System.Xml.XmlNodeList children = datatypeElement.ChildNodes; int compNum = 0; for (int i = 0; i < children.Count; i++) { if (System.Convert.ToInt16(children.Item(i).NodeType) == (short)System.Xml.XmlNodeType.Element) { parse(datatypeObject.getComponent(compNum), (System.Xml.XmlElement)children.Item(i)); compNum++; } } } else { Type[] children = datatypeObject.Components; for (int i = 0; i < children.Length; i++) { System.Xml.XmlNodeList matchingElements = datatypeElement.GetElementsByTagName(makeElementName(datatypeObject, i + 1)); if (matchingElements.Count > 0) { parse(children[i], (System.Xml.XmlElement)matchingElements.Item(0)); //components don't repeat - use 1st } } } }
private IEnumerable<SubjectConfirmation> buildConfirmations(XmlElement element) { foreach (XmlElement confirmationElement in element.GetElementsByTagName(SubjectConfirmation, AssertionXsd)) { yield return new SubjectConfirmation(confirmationElement); } }
/// <summary> /// Create a network activation scheme from the scheme setting in the provided config XML. /// </summary> /// <returns></returns> public static NetworkActivationScheme CreateActivationScheme(XmlElement xmlConfig, string activationElemName) { // Get root activation element. XmlNodeList nodeList = xmlConfig.GetElementsByTagName(activationElemName, ""); if (nodeList.Count != 1) { throw new ArgumentException("Missing or invalid activation XML config setting."); } XmlElement xmlActivation = nodeList[0] as XmlElement; string schemeStr = XmlUtils.TryGetValueAsString(xmlActivation, "Scheme"); switch (schemeStr) { case "Acyclic": return NetworkActivationScheme.CreateAcyclicScheme(); case "CyclicFixedIters": int iters = XmlUtils.GetValueAsInt(xmlActivation, "Iters"); return NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(iters); case "CyclicRelax": double deltaThreshold = XmlUtils.GetValueAsDouble(xmlActivation, "Threshold"); int maxIters = XmlUtils.GetValueAsInt(xmlActivation, "MaxIters"); return NetworkActivationScheme.CreateCyclicRelaxingActivationScheme(deltaThreshold, maxIters); } throw new ArgumentException(string.Format("Invalid or missing ActivationScheme XML config setting [{0}]", schemeStr)); }
/// <summary> /// Creates a DBMLTable for a document, with the details held in xml element /// </summary> /// <param name="doc">The DBMLDocument this table belongs to</param> /// <param name="e">The XmlElement containing the details of the table</param> public DBMLTable(DBMLDoc doc, XmlElement e) { _elem = e; _tableName = _elem.GetAttribute("Name"); if(string.IsNullOrEmpty(_tableName)) throw new ArgumentException("Cannot get table name"); XmlNodeList nl = _elem.GetElementsByTagName("Type"); if(nl.Count != 1 || nl[0].NodeType != XmlNodeType.Element) throw new ArgumentException("Cannot Identity type for table " + _tableName); _typeElem = nl[0] as XmlElement; _cols = new DBMLColumnList(); try { foreach(XmlNode n in _typeElem.ChildNodes) { XmlElement ce = n as XmlElement; if(ce != null && ce.Name == "Column") _cols.Add(new DBMLColumn(ce)); } } catch(Exception ex) { throw new ArgumentException(string.Format("Problem parsing table {0} {1}", _tableName, ex.Message)); } }
//METHODS //creates preference object from XMLElement public Preference(XmlElement fileElement) { serviceName = fileElement.GetAttribute("name"); if (serviceName.Length == 0) { throw new Exception("XML Element was not well formed"); } XmlNodeList children = fileElement.GetElementsByTagName("preference"); if (children.Count != 1) { throw new Exception("XML Element was not well formed"); } XmlElement preference = (XmlElement)children[0]; string settingString = preference.GetAttribute("setting"); if (settingString == "default") { setting = settings.defaultDisplay; } else if (settingString == "always") { setting = settings.alwaysDisplay; } else if (settingString == "never") { setting = settings.neverDisplay; } else { throw new Exception("XML Element was not well formed"); } }
private IEnumerable<SubjectConfirmationData> buildData(XmlElement element) { foreach (XmlElement dataElement in element.GetElementsByTagName(SubjectConfirmationData, AssertionXsd)) { yield return new SubjectConfirmationData(dataElement); } }
public Media(XmlElement element) { Title = Util.ChildValue(element, "title"); Player = Util.ChildValue(element, "player"); Link = Util.ChildValue(element, "link"); Thumbnails = new ThumbnailList(); foreach (XmlElement child in element.GetElementsByTagName("thumbnail")) { Thumbnails.Add(new Thumbnail(child)); } Content = new ContentList(); foreach (XmlElement child in element.GetElementsByTagName("content")) { Content.Add(new Content(child)); } }
internal static XmlElement GetLinkElement(XmlElement constrainedElement) { if (constrainedElement.Name == "home:ConstrainedQuicklink" || constrainedElement.Name == "constraints:ConstrainedItem") return (XmlElement)constrainedElement.GetElementsByTagName("Value")[0].FirstChild; else return constrainedElement; }
public void loadXMLFiles() { try { txtOutput.Text += "\n" + pathFiles + "\n"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(pathFiles); System.Xml.XmlElement root = doc.DocumentElement; System.Xml.XmlNodeList lst = root.GetElementsByTagName("Item"); foreach (System.Xml.XmlNode n in lst) { try { lviFileList.Items.Add(n.InnerText); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Returns the first child element found that has the specified name. /// </summary> /// <param name="parentElement"></param> /// <param name="childElementName"></param> /// <returns></returns> public static XmlElement GetChildElement(XmlElement parentElement, string childElementName) { XmlNodeList nodes = parentElement.GetElementsByTagName(childElementName); if(nodes.Count == 0) return null; return nodes[0] as XmlElement; }
private void parseReps(Segment segmentObject, System.Xml.XmlElement segmentElement, System.String fieldName, int fieldNum) { System.Xml.XmlNodeList reps = segmentElement.GetElementsByTagName(fieldName); for (int i = 0; i < reps.Count; i++) { parse(segmentObject.getField(fieldNum, i), (System.Xml.XmlElement)reps.Item(i)); } }
public static System.Xml.XmlNodeList getSubNodes(System.Xml.XmlElement node) { // GHT alternative for GetElementsByTagName("*") // System.Collections.ArrayList nodeArrayList = new System.Collections.ArrayList (); // getAllNodesRecursively (node, nodeArrayList); // return new XmlNodeArrayList (nodeArrayList); // GHT alternative for GetElementsByTagName("*") return(node.GetElementsByTagName("*")); }
/// <summary> Returns the first child element of the given parent that matches the given /// tag name. Returns null if no instance of the expected element is present. /// </summary> private System.Xml.XmlElement getFirstElementByTagName(System.String name, System.Xml.XmlElement parent) { System.Xml.XmlNodeList nl = parent.GetElementsByTagName(name); System.Xml.XmlElement ret = null; if (nl.Count > 0) { ret = (System.Xml.XmlElement)nl.Item(0); } return(ret); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(@"C:\Users\panmo\source\repos\EdgeEnergy\App_Data\XMLFile1.xml"); System.Xml.XmlElement root = doc.DocumentElement; System.Xml.XmlNodeList lst = root.GetElementsByTagName("list"); foreach (System.Xml.XmlNode n in lst) { ListBox1.Items.Add(n.InnerText); } } }
/// <summary> Parses an XML profile string into a RuntimeProfile object. </summary> public virtual RuntimeProfile parse(System.String profileString) { RuntimeProfile profile = new RuntimeProfile(); System.Xml.XmlDocument doc = parseIntoDOM(profileString); System.Xml.XmlElement root = (System.Xml.XmlElement)doc.DocumentElement; profile.setHL7Version(root.GetAttribute("HL7Version")); //get static definition System.Xml.XmlNodeList nl = root.GetElementsByTagName("HL7v2xStaticDef"); System.Xml.XmlElement staticDef = (System.Xml.XmlElement)nl.Item(0); StaticDef sd = parseStaticProfile(staticDef); profile.Message = sd; return(profile); }
public void ShowMultiKeyDialog(System.Xml.XmlElement xmlKeyRing) { this.cmbSecretKeys.Items.Clear(); this.cmbSecretKeys.Enabled = true; XmlNodeList xnlSecretKeys = xmlKeyRing.GetElementsByTagName("SecretKey"); IEnumerator ieKeys = xnlSecretKeys.GetEnumerator(); while (ieKeys.MoveNext()) { XmlElement xmlKey = (XmlElement)ieKeys.Current; ComboBoxKeyItem cbkiKey = new ComboBoxKeyItem(xmlKey); cmbSecretKeys.Items.Add(cbkiKey); } cmbSecretKeys.SelectedIndex = 0; this.ShowDialog(); }
private List <string> GetValue(System.Xml.XmlElement instanceElement) { XmlNodeList nodes = instanceElement.GetElementsByTagName("FindItem"); List <string> Value = null; //string[] database2 = new string[] { "One", "Two" }; if (nodes.Count > 0) { Value = new List <string>(); foreach (XmlNode item in nodes) { Value.Add(item.Attributes["Value"].Value); } } return(Value); }
private List <string> GetDatabases(System.Xml.XmlElement instanceElement) { XmlNodeList databaseNodes = instanceElement.GetElementsByTagName("Database"); List <string> databases = null; //string[] database2 = new string[] { "One", "Two" }; if (databaseNodes.Count > 0) { databases = new List <string>(); foreach (XmlNode item in databaseNodes) { databases.Add(item.Attributes["Name"].Value); } } return(databases); }
public void calcula() { try { Double totalvenda = 0; Double totalimposto = 0; DirectoryInfo Dir = new DirectoryInfo(@"C:\Users\Natanniel\Desktop\201803"); //DirectoryInfo Dir = new DirectoryInfo(@"C:\Users\Natanniel\Desktop\cancelamentos_201708"); // Busca automaticamente todos os arquivos em todos os subdiretórios FileInfo[] Files = Dir.GetFiles("*", SearchOption.AllDirectories); DataTable dt_produtos = new DataTable(); String[,] itens = new String[5000, 2]; int linha = 0; foreach (FileInfo File in Files) { System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.Load(File.FullName); System.Xml.XmlElement root = xml.DocumentElement; System.Xml.XmlNodeList nodeList = root.GetElementsByTagName("total"); totalvenda += Double.Parse(nodeList[0]["vCFe"].InnerText, System.Globalization.CultureInfo.InvariantCulture); } dt_produtos = new DataTable(); dt_produtos.Columns.Add("Código Produto", typeof(string)); dt_produtos.Columns.Add("Quantidade Produto", typeof(string)); for (int x = 0; x < linha; x++) { dt_produtos.Rows.Add(itens[x, 0], itens[x, 1]); } super_grid spg = new super_grid(dt_produtos); spg.ShowDialog(); } catch { } }
public void setXmlInfo(System.Xml.XmlDocument To_JavaXml, System.Xml.XmlElement engBaseInfo, MDL.T_Projects project = null, System.Xml.XmlElement root = null) { List <T_Model> outList = new List <T_Model>(); outList = ProjectXML_Factory.setXmlInfo(To_JavaXml, project, "queryByProjectNO", engBaseInfo, "Archive", " where ProjectNO='" + project.ProjectNO + "'"); List <string> list = new List <string>(); if (outList != null) { foreach (var item in outList) { XmlNodeList xmlList = engBaseInfo.GetElementsByTagName(item.MappColumn); if (xmlList.Count == 0) { X_temp = To_JavaXml.CreateElement(item.MappColumn); } else { continue; } if (item.MappColumn == "archWidth") { string jhlx = obj.jhlx.Replace("公分案卷盒", ""); jhlx = jhlx.Replace("公分", ""); jhlx = jhlx.Replace("案卷盒", ""); X_temp.SetAttribute("value", jhlx); } else { X_temp.SetAttribute("value", item.Default); } X_temp.SetAttribute("description", item.Description); engBaseInfo.AppendChild(X_temp); } } }
protected override void ReadXml(object entity, System.Xml.XmlElement parent, IFormatProvider formatProvider, string localName, bool mandatory) { XmlNodeList nodes = parent.GetElementsByTagName(localName); if (nodes.Count > 0) { IList list = (IList)GetValue(entity); if (list == null) { list = (IList)Activator.CreateInstance(DataType); SetValue(entity, list); } foreach (XmlElement element in nodes) { object child = _Constructor.Invoke(null); foreach (XmlAspectMember xam in _Aspect) { xam.ReadXml(child, element, formatProvider); } list.Add(child); } } }
private void SourceField_SelectionChanged(object sender, SelectionChangedEventArgs e) { var comboBox = sender as ComboBox; if (this._skipSelectionChanged || comboBox.IsLoaded == false) { return; } bool doSave = false; if (((ComboBox)sender).IsLoaded && (e.AddedItems.Count > 0 || e.RemovedItems.Count > 0) && FieldGrid.SelectedIndex != -1) { // disregard SelectionChangedEvent fired on population from binding for (Visual visual = (Visual)sender; visual != null; visual = (Visual)VisualTreeHelper.GetParent(visual)) { // Traverse tree to find correct selected item if (visual is DataGridRow) { DataGridRow row = visual as DataGridRow; object val = row.Item; System.Xml.XmlElement xml = val as System.Xml.XmlElement; if (xml != null) { try { string nm = xml.GetElementsByTagName("TargetName")[0].InnerText; string xmlname = ""; try { xmlname = _xml.SelectSingleNode("//Field[position()=" + (_selectedRowNum + 1).ToString() + "]/TargetName").InnerText; } catch { } if (nm == xmlname) { doSave = true; break; } } catch { } } } } } int fieldnum = FieldGrid.SelectedIndex + 1; var nodes = getFieldNodes(fieldnum); if (nodes != null && comboBox != null && comboBox.SelectedValue != null && doSave == true) { try { string selected = comboBox.SelectedValue.ToString(); this._skipSelectionChanged = true; if (nodes.Count == 1) { // source field selection should change to Copy var node = nodes.Item(0).SelectSingleNode("Method"); var nodeField = nodes.Item(0).SelectSingleNode("SourceName"); if (selected == _noneField && comboMethod.SelectedIndex != 0) { node.InnerText = "None"; nodeField.InnerText = selected; comboMethod.SelectedIndex = 0; saveFieldGrid(); } else if (selected != _noneField) { node.InnerText = "Copy"; nodeField.InnerText = selected; comboMethod.SelectedIndex = 1; saveFieldGrid(); } _selectedRowNum = fieldnum; this._skipSelectionChanged = false; } } catch { } } }
//──────────────────────────────────────── #endregion #region アクション //──────────────────────────────────────── /// <summary> /// 『Aa_Tool.xml/<editor>要素』または、『Aa_Editor.xml/<ルート>要素』を読み取ります。 /// <f-set-var>を読み取った場合、逐次、変数モデルに追加していきます。 /// </summary> public void LoadFile_Aaxml( Expression_Node_Filepath ec_Fpath_Aaxml, MemoryVariables moVariables, Log_Reports log_Reports ) { Log_Method log_Method = new Log_MethodImpl(0); log_Method.BeginMethod(Info_MiddleImpl.Name_Library, this, "LoadFile_Aaxml", log_Reports); string sFpatha; { sFpatha = ec_Fpath_Aaxml.Execute4_OnExpressionString( EnumHitcount.Unconstraint, log_Reports //out sErrorMsg ); //絶対ファイルパス if (!log_Reports.Successful) { // 既エラー。 goto gt_EndMethod; } } System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); Exception err_Excp; try { xDoc.Load(sFpatha); // ルート要素を取得 System.Xml.XmlElement xRoot = xDoc.DocumentElement; // <f-set-var>要素を列挙 XmlNodeList xNl_Fsetvar = xRoot.GetElementsByTagName(NamesNode.S_F_SET_VAR); foreach (XmlNode xNode_Fsetvar in xNl_Fsetvar) { if (XmlNodeType.Element == xNode_Fsetvar.NodeType) { //<f-set-var>要素 XmlElement xFsetvar = (XmlElement)xNode_Fsetvar; //name-var属性 string sNamevar = xFsetvar.GetAttribute(PmNames.S_NAME_VAR.Name_Attribute); //folder属性 string sFolder = xFsetvar.GetAttribute(PmNames.S_FOLDER.Name_Attribute); //value属性 string sValue = xFsetvar.GetAttribute(PmNames.S_VALUE.Name_Attribute); //description属性 string sDescription = xFsetvar.GetAttribute(PmNames.S_DESCRIPTION.Name_Attribute); Configurationtree_Node cf_Fsetvar = new Configurationtree_NodeImpl(NamesNode.S_F_SET_VAR, null//todo:親ノード ); cf_Fsetvar.Dictionary_Attribute.Set(PmNames.S_NAME_VAR.Name_Pm, sNamevar, log_Reports); cf_Fsetvar.Dictionary_Attribute.Set(PmNames.S_FOLDER.Name_Pm, sFolder, log_Reports); cf_Fsetvar.Dictionary_Attribute.Set(PmNames.S_VALUE.Name_Pm, sValue, log_Reports); cf_Fsetvar.Dictionary_Attribute.Set(PmNames.S_DESCRIPTION.Name_Pm, sDescription, log_Reports); this.Dictionary_Fsetvar_Configurationtree.List_Child.Add(cf_Fsetvar, log_Reports); //変数への追加 { if ( NamesVar.Test_Filepath(sNamevar) ) { // ファイルパスの場合 Configurationtree_NodeFilepath cf_Fpath = new Configurationtree_NodeFilepathImpl("name-var=[" + sNamevar + "]", ec_Fpath_Aaxml.Cur_Configuration); cf_Fpath.InitPath( sValue, log_Reports ); if ("" != sFolder) { Expression_Node_Filepath ec_Folder = moVariables.GetExpressionfilepathByVariablename(new Expression_Leaf_StringImpl(sFolder, ec_Fpath_Aaxml, cf_Fsetvar), true, log_Reports); if (log_Reports.Successful) { cf_Fpath.SetDirectory_Base( ec_Folder.Execute4_OnExpressionString(EnumHitcount.Unconstraint, log_Reports) //sFolder ); } } if (log_Reports.Successful) { Expression_Node_Filepath ec_Fpath = new Expression_Node_FilepathImpl(cf_Fpath); moVariables.PutFilepath( sNamevar, ec_Fpath, true, log_Reports ); } } else { // ファイルパスでない場合 moVariables.PutString( sNamevar, sValue, log_Reports ); } } } if (!log_Reports.Successful) { //既エラー break; } } if (!log_Reports.Successful) { // 既エラー。 goto gt_EndMethod; } } catch (System.IO.IOException ex) { // 既エラー。 err_Excp = ex; goto gt_Error_IOException; } goto gt_EndMethod; // // #region 異常系 //──────────────────────────────────────── gt_Error_IOException: if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー283!", log_Method); StringBuilder s = new StringBuilder(); s.Append("エディター設定ファイルが見つかりません。:" + err_Excp.Message); //ヒント s.Append(r.Message_Configuration(ec_Fpath_Aaxml.Cur_Configuration)); r.Message = s.ToString(); log_Reports.EndCreateReport(); } goto gt_EndMethod; //──────────────────────────────────────── #endregion // // gt_EndMethod: log_Method.EndMethod(log_Reports); return; }
public MemoryGloballistconfig Perform( string sFpath_Glcnf, Log_Reports log_Reports ) { Log_Method pg_Method = new Log_MethodImpl(0); pg_Method.BeginMethod(Info_Operating.Name_Library, this, "Perform", log_Reports); // グローバルリスト・コンフィグ設定ファイルの内容。 MemoryGloballistconfig moGlcnf = new MemoryGloballistconfigImpl(); Configurationtree_Node parent_Configurationtree_Node = new Configurationtree_NodeImpl("グローバルリスト設定", null); Configurationtree_NodeFilepath cf_Fpath = new Configurationtree_NodeFilepathImpl("ファイルパス出典未指定L03_2", parent_Configurationtree_Node); cf_Fpath.InitPath(sFpath_Glcnf, log_Reports); if (!log_Reports.Successful) { // 既エラー。 goto gt_EndMethod; } Expression_Node_Filepath ec_Fpath = new Expression_Node_FilepathImpl(cf_Fpath); string sFpatha_Xml = ec_Fpath.Execute4_OnExpressionString( EnumHitcount.Unconstraint, log_Reports); if (!log_Reports.Successful) { // 既エラー。 goto gt_EndMethod; } System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); if (log_Reports.Successful) { // 正常時 try { // ファイルの読込み doc.Load(sFpatha_Xml); } catch (System.ArgumentException ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー0800206!", pg_Method); StringBuilder t = new StringBuilder(); t.Append("『SRSグローバルリスト』設定ファイルを読込もうとしたら、エラーが発生しました。"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("ファイル=["); t.Append(sFpath_Glcnf); t.Append("]"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("もしかすると:"); t.Append(Environment.NewLine); t.Append(" ・ファイルパスが間違っているか、未入力なのかも知れません。ファイルパスを指定してください。"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("例外メッセージ:["); t.Append(ex.GetType().Name); t.Append("]:"); t.Append(ex.Message); r.Message = t.ToString(); log_Reports.EndCreateReport(); } } catch (System.Exception ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー0800205!", pg_Method); StringBuilder t = new StringBuilder(); t.Append("『SRSグローバルリスト』設定ファイルの読込中にエラーが発生しました。"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("ファイル=["); t.Append(sFpath_Glcnf); t.Append("]"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("もしかすると:"); t.Append(Environment.NewLine); t.Append(" ・読込む設定ファイルを間違えている? それは『SRSグローバルリスト 設定ファイル』で合っていますか?"); t.Append(Environment.NewLine); t.Append(" ・読込んだ設定ファイルの内容に間違いがある?"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("例外メッセージ:["); t.Append(ex.GetType().Name); t.Append("]:"); t.Append(ex.Message); r.Message = t.ToString(); log_Reports.EndCreateReport(); } } } if (log_Reports.Successful) { // 正常時 try { // ルート要素を取得 System.Xml.XmlElement root = doc.DocumentElement; // type要素を列挙 System.Xml.XmlNodeList typeNL = root.GetElementsByTagName("type"); for (int nTypeIndex = 0; nTypeIndex < typeNL.Count; nTypeIndex++) { XmlNode x_TypeNode = typeNL.Item(nTypeIndex); if (log_Reports.Successful) { // 正常時 if (XmlNodeType.Element == x_TypeNode.NodeType) { // // type要素 // XmlElement x_TypeElm = (XmlElement)x_TypeNode; string sType = x_TypeElm.Attributes.GetNamedItem(SrsAttrName.S_NAME).Value; GloballistconfigTypesectionImpl typeSection = new GloballistconfigTypesectionImpl(); typeSection.Name_Type = sType; moGlcnf.TypesectionList.List_Item.Add(typeSection); } } } // human要素を列挙 System.Xml.XmlNodeList x_HumanNL = root.GetElementsByTagName("human"); for (int nHumanIndex = 0; nHumanIndex < x_HumanNL.Count; nHumanIndex++) { XmlNode x_HumanNode = x_HumanNL.Item(nHumanIndex); if (log_Reports.Successful) { // 正常時 if (XmlNodeType.Element == x_HumanNode.NodeType) { // // human要素 // XmlElement x_HumanElm = (XmlElement)x_HumanNode; GloballistconfigHuman human = new GloballistconfigHumanImpl(); human.Name = x_HumanElm.Attributes.GetNamedItem(SrsAttrName.S_NAME).Value; moGlcnf.Dictionary_Human.Add(human.Name, human); // variable要素を列挙 System.Xml.XmlNodeList x_VariableNL = x_HumanElm.GetElementsByTagName("variable"); for (int n_VariableIndex = 0; n_VariableIndex < x_VariableNL.Count; n_VariableIndex++) { XmlNode x_VariableNode = x_VariableNL.Item(n_VariableIndex); if (XmlNodeType.Element == x_VariableNode.NodeType) { // // variable要素 // XmlElement x_VariableElm = (XmlElement)x_VariableNode; GloballistconfigVariable variable = new GloballistconfigVariableImpl(); variable.Name_Type = x_VariableElm.Attributes.GetNamedItem("type").Value; // 変数の連想配列に、項目を追加 if (human.Dictionary_Variable.ContainsKey(variable.Name_Type)) { // エラー if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー1002!", pg_Method); r.Message = "指定された変数の型[" + variable.Name_Type + "]が、重複されて記述されています。"; log_Reports.EndCreateReport(); } } else { human.Dictionary_Variable.Add(variable.Name_Type, variable); // number要素を列挙 System.Xml.XmlNodeList numberNL = x_VariableElm.GetElementsByTagName("number"); for (int numberIndex = 0; numberIndex < numberNL.Count; numberIndex++) { XmlNode numberNode = numberNL.Item(numberIndex); if (XmlNodeType.Element == numberNode.NodeType) { // // number要素 // XmlElement numberElm = (XmlElement)numberNode; GloballistconfigNumber numberObj = new GloballistconfigNumberImpl(); numberObj.Text_Range = numberElm.Attributes.GetNamedItem("range").Value; Int_HumaninputImpl oPriority = new Int_HumaninputImpl("!ハードコーディング_LoaderOfGlobalListConfigXml"); oPriority.Text = numberElm.Attributes.GetNamedItem("priority").Value; numberObj.Priority = oPriority; // 変数の連想配列に、変数番号オブジェクトを追加 variable.Dictionary_Number.Add(numberObj.Text_Range, numberObj); } } } } } } } } } catch (System.IO.IOException ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー080103!", pg_Method); r.Message = "『SRSグローバルリスト』設定ファイルが見つかりません。:" + ex.Message; log_Reports.EndCreateReport(); } } catch (System.Exception ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー0800204!", pg_Method); StringBuilder t = new StringBuilder(); t.Append("『SRSグローバルリスト』設定ファイルの読込中にエラーが発生しました。"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("ファイル=["); t.Append(sFpath_Glcnf); t.Append("]"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("もしかすると:"); t.Append(Environment.NewLine); t.Append(" ・読込む設定ファイルを間違えている? それは『SRSグローバルリスト 設定ファイル』で合っていますか?"); t.Append(Environment.NewLine); t.Append(" ・読込んだ設定ファイルの内容に間違いがある?"); t.Append(Environment.NewLine); t.Append(Environment.NewLine); t.Append("例外メッセージ:["); t.Append(ex.GetType().Name); t.Append("]:"); t.Append(ex.Message); r.Message = t.ToString(); log_Reports.EndCreateReport(); } } } // // // // gt_EndMethod: pg_Method.EndMethod(log_Reports); return(moGlcnf); }
public bool LoadLabelInfo(MapWindow.Interfaces.IMapWin m_MapWin, MapWindow.Interfaces.Layer layer, ref Forms.Label label, System.Windows.Forms.Form owner) { if (layer == null) { return(false); } //make sure the file exists string filename = ""; if (m_MapWin.View.LabelsUseProjectLevel) { if (m_MapWin.Project.FileName != null && m_MapWin.Project.FileName.Trim() != "") { filename = System.IO.Path.GetFileNameWithoutExtension(m_MapWin.Project.FileName) + @"\" + System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(layer.FileName), ".lbl"); } } if (filename == "" || !System.IO.File.Exists(filename)) { filename = System.IO.Path.ChangeExtension(layer.FileName, ".lbl"); } if (!System.IO.File.Exists(filename)) { return(false); } try { //load the xml file m_doc.Load(filename); //get the root of the file System.Xml.XmlElement root = m_doc.DocumentElement; label.points = new System.Collections.ArrayList(); label.labelShape = new System.Collections.ArrayList(); XmlNodeList nodeList = root.GetElementsByTagName("Labels"); //get the font int field = int.Parse(nodeList[0].Attributes.GetNamedItem("Field").InnerText); int field2 = 0; if (nodeList[0].Attributes.GetNamedItem("Field2") != null) { field2 = int.Parse(nodeList[0].Attributes.GetNamedItem("Field2").InnerText); } string fontName = nodeList[0].Attributes.GetNamedItem("Font").InnerText; float size = float.Parse(nodeList[0].Attributes.GetNamedItem("Size").InnerText); System.Drawing.Color color = System.Drawing.Color.FromArgb(int.Parse(nodeList[0].Attributes.GetNamedItem("Color").InnerText)); int justification = int.Parse(nodeList[0].Attributes.GetNamedItem("Justification").InnerText); bool UseMinZoom = bool.Parse(nodeList[0].Attributes.GetNamedItem("UseMinZoomLevel").InnerText); bool Scaled = false; bool UseShadows = false; System.Drawing.Color ShadowColor = System.Drawing.Color.White; int Offset = 0; double StandardViewWidth = 0.0; bool UseLabelCollision = false; bool RemoveDuplicateLabels = false; string RotationField = ""; try { if (nodeList[0].Attributes.GetNamedItem("Scaled") != null) { Scaled = bool.Parse(nodeList[0].Attributes.GetNamedItem("Scaled").InnerText); } if (nodeList[0].Attributes.GetNamedItem("UseShadows") != null) { UseShadows = bool.Parse(nodeList[0].Attributes.GetNamedItem("UseShadows").InnerText); } if (nodeList[0].Attributes.GetNamedItem("ShadowColor") != null) { ShadowColor = System.Drawing.Color.FromArgb(int.Parse(nodeList[0].Attributes.GetNamedItem("ShadowColor").InnerText)); } if (nodeList[0].Attributes.GetNamedItem("Offset") != null) { Offset = int.Parse(nodeList[0].Attributes.GetNamedItem("Offset").InnerText); } if (nodeList[0].Attributes.GetNamedItem("StandardViewWidth") != null) { StandardViewWidth = double.Parse(nodeList[0].Attributes.GetNamedItem("StandardViewWidth").InnerText); } } catch { Scaled = false; UseShadows = false; ShadowColor = System.Drawing.Color.White; Offset = 0; StandardViewWidth = 0.0; } if (nodeList[0].Attributes.GetNamedItem("UseLabelCollision") != null) { UseLabelCollision = bool.Parse(nodeList[0].Attributes.GetNamedItem("UseLabelCollision").InnerText); } if (nodeList[0].Attributes.GetNamedItem("RemoveDuplicateLabels") != null) { RemoveDuplicateLabels = bool.Parse(nodeList[0].Attributes.GetNamedItem("RemoveDuplicateLabels").InnerText); } if (nodeList[0].Attributes.GetNamedItem("RotationField") != null) { RotationField = nodeList[0].Attributes.GetNamedItem("RotationField").InnerText; } double xMin = double.Parse(nodeList[0].Attributes.GetNamedItem("xMin").InnerText); double yMin = double.Parse(nodeList[0].Attributes.GetNamedItem("yMin").InnerText); double xMax = double.Parse(nodeList[0].Attributes.GetNamedItem("xMax").InnerText); double yMax = double.Parse(nodeList[0].Attributes.GetNamedItem("yMax").InnerText); //set all the properties of the label label.font = new System.Drawing.Font(fontName, size); label.color = color; label.field = field; label.field2 = field2; label.handle = layer.Handle; label.alignment = (MapWinGIS.tkHJustification)justification; label.UseMinExtents = UseMinZoom; label.Scaled = Scaled; label.UseShadows = UseShadows; label.shadowColor = ShadowColor; label.Offset = Offset; label.StandardViewWidth = StandardViewWidth; label.RotationField = RotationField; if (nodeList[0].Attributes.GetNamedItem("UseLabelCollision") != null) { label.UseLabelCollision = UseLabelCollision; } if (nodeList[0].Attributes.GetNamedItem("RemoveDuplicateLabels") != null) { label.RemoveDuplicates = RemoveDuplicateLabels; } if (nodeList[0].Attributes.GetNamedItem("AppendLine1") != null) { label.AppendLine1 = nodeList[0].Attributes.GetNamedItem("AppendLine1").InnerText; } if (nodeList[0].Attributes.GetNamedItem("AppendLine2") != null) { label.AppendLine2 = nodeList[0].Attributes.GetNamedItem("AppendLine2").InnerText; } if (nodeList[0].Attributes.GetNamedItem("PrependLine1") != null) { label.PrependLine1 = nodeList[0].Attributes.GetNamedItem("PrependLine1").InnerText; } if (nodeList[0].Attributes.GetNamedItem("PrependLine2") != null) { label.PrependLine2 = nodeList[0].Attributes.GetNamedItem("PrependLine2").InnerText; } label.extents = new MapWinGIS.ExtentsClass(); label.extents.SetBounds(xMin, yMin, 0, xMax, yMax, 0); label.Modified = false; label.LabelExtentsChanged = false; label.updateHeaderOnly = true; //add all the points to this label Forms.Point p; XmlNode node; double x, y, rotation = 0; System.Collections.IEnumerator enumerator = nodeList[0].ChildNodes.GetEnumerator(); while (enumerator.MoveNext()) { node = (XmlNode)enumerator.Current; x = double.Parse(node.Attributes.GetNamedItem("X").InnerText); y = double.Parse(node.Attributes.GetNamedItem("Y").InnerText); if (nodeList[0].Attributes.GetNamedItem("Rotation") != null) { rotation = double.Parse(node.Attributes.GetNamedItem("Rotation").InnerText); } p = new Forms.Point(); p.x = x; p.y = y; p.rotation = rotation; label.points.Add(p); } label.xml_LblFile = m_doc.InnerXml; } catch { return(false); } return(true); }
public void LoadUserCnf(out string sErrorMsg) { // 絶対ファイルパス string sFpatha = this.GetUserCnf(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); Exception error_excp; try { // ファイルの読込み doc.Load(sFpatha); } catch (System.ArgumentException ex) { // エラー goto error_filePath; } catch (System.Exception ex) { // エラー error_excp = ex; goto error_read; } // ルート要素 System.Xml.XmlElement root = doc.DocumentElement; // userノード System.Xml.XmlNodeList userNL = root.GetElementsByTagName("user"); for (int i = 0; i < userNL.Count; i++) { XmlNode nd = userNL.Item(i); if (XmlNodeType.Element == nd.NodeType) { // // <user> // XmlElement elm = (XmlElement)nd; this.SUser = elm.Attributes.GetNamedItem("value").Value; // 最初の1個で終了。 break; } } // versionノード System.Xml.XmlNodeList versionNL = root.GetElementsByTagName("version"); for (int i = 0; i < versionNL.Count; i++) { XmlNode nd = versionNL.Item(i); if (XmlNodeType.Element == nd.NodeType) { // // <version> // XmlElement elm = (XmlElement)nd; this.SVer = elm.Attributes.GetNamedItem("value").Value; // 最初の1個で終了。 break; } } // numberノード System.Xml.XmlNodeList numberNL = root.GetElementsByTagName("number"); for (int i = 0; i < numberNL.Count; i++) { XmlNode nd = numberNL.Item(i); if (XmlNodeType.Element == nd.NodeType) { // // <version> // XmlElement elm = (XmlElement)nd; int next = 0; int.TryParse(elm.Attributes.GetNamedItem("value").Value, out next); this.Num = next; // 最初の1個で終了。 break; } } sErrorMsg = ""; goto process_end; // // error_filePath: { StringBuilder t = new StringBuilder(); t.Append("エラー:ユーザー設定ファイルパス=["); t.Append(sFpatha); t.Append("]"); sErrorMsg = t.ToString(); } goto process_end; // // error_read: { StringBuilder t = new StringBuilder(); t.Append("エラー:ユーザー設定ファイルパス読取失敗=["); t.Append(error_excp.Message); t.Append("]"); sErrorMsg = t.ToString(); } goto process_end; // // // // process_end: return; }
/// <summary> /// XML形式で書出し。 /// </summary> /// <param name="filePath"></param> /// <param name="encoding"></param> /// <param name="doc"></param> /// <param name="log_Reports"></param> public bool Perform( string sFpath, Encoding encoding, XmlDocument doc, Log_Reports log_Reports ) { Log_Method pg_Method = new Log_MethodImpl(0); pg_Method.BeginMethod(Info_Operating.Name_Library, this, "Perform", log_Reports); bool bResult; try { // ルート要素を取得 System.Xml.XmlElement root = doc.DocumentElement; // sample要素を列挙 System.Xml.XmlNodeList nodeList = root.GetElementsByTagName("sample"); // XMLの保存方法を設定します。 System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sFpath, encoding); writer.Formatting = System.Xml.Formatting.Indented; writer.Indentation = 4; try { doc.Save(writer); bResult = true; goto gt_EndMethod; } catch (Exception ex) { // エラー処理 if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー0801087!", pg_Method); r.Message = "[" + ex.GetType().Name + "]:" + ex.Message; log_Reports.EndCreateReport(); } } finally { writer.Close(); } } catch (System.Xml.XmlException ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー1086!", pg_Method); r.Message = ex.Message; log_Reports.EndCreateReport(); } } catch (System.IO.IOException ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー1085!", pg_Method); r.Message = ex.Message; log_Reports.EndCreateReport(); } } catch (System.Exception ex) { if (log_Reports.CanCreateReport) { Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error); r.SetTitle("▲エラー0801084!", pg_Method); r.Message = "[" + ex.GetType().Name + "]:" + ex.Message; log_Reports.EndCreateReport(); } } bResult = false; goto gt_EndMethod; gt_EndMethod: pg_Method.EndMethod(log_Reports); return(bResult); }
/// <summary> /// 解析返回的XML /// </summary> /// <param name="s"></param> /// <returns></returns> private Hashtable NodeXml(string s) { s = ((s.Replace("<", "<")).Replace(">", ">")).Replace(""", "\""); Hashtable result = new Hashtable(); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(s); /*解析题目原始信息*/ XmlNode raw = (((((doc.SelectSingleNode("invoke"))).SelectSingleNode("arguments")).SelectSingleNode("string")).SelectSingleNode("result")).SelectSingleNode("raw"); result["scaleNum"] = raw.ChildNodes.Count; /*解析结果解释和基本信息部分*/ XmlNodeList rule = doc.GetElementsByTagName("base"); //基本部分 result["scaleName"] = ((XmlElement)rule[0]).GetElementsByTagName("names")[0].InnerText; //量表名称 result["intro"] = ((XmlElement)rule[0]).GetElementsByTagName("intro")[0].InnerText; //量表概述 XmlNodeList explain = ((XmlElement)rule[0]).GetElementsByTagName("column"); ArrayList ruleList = new ArrayList(); for (int n = 0; n < explain.Count; n++) { Hashtable ruleTmp = new Hashtable(); String ruleKey = explain[n].Attributes.GetNamedItem("id").Value; int ruleNum = explain[n].Attributes.Count; if (ruleNum > 1) { String ruleExp = explain[n].Attributes.GetNamedItem("Explain").Value; ruleTmp["ruleExp"] = ruleExp; } else { ruleTmp["ruleExp"] = ""; } ruleTmp["ruleName"] = ruleKey; String[] ruleContents = explain[n].InnerText.Split(new char[] { '|' }); if (ruleContents.Length >= 3) { ArrayList tmpList = new ArrayList(); for (int rc = 0; rc < ruleContents.Length; rc++) { Hashtable nums = new Hashtable(); String lowNum = (ruleContents[rc].Split(new char[] { ',' }))[0]; String highNum = (ruleContents[rc].Split(new char[] { ',' }))[1]; nums["low"] = lowNum; nums["high"] = highNum; nums["scoreLevel"] = (ruleContents[rc].Split(new char[] { ',' }))[2]; tmpList.Add(nums); } ruleTmp["ruleLevels"] = tmpList; } else { ruleTmp["ruleLevels"] = new ArrayList(); } ruleList.Add(ruleTmp); } result["rule"] = ruleList; /*解析结果部分*/ XmlNodeList results = doc.GetElementsByTagName("resultList"); XmlNodeList resultList = ((XmlElement)results[0]).GetElementsByTagName("column"); //取得结果的详细解释 XmlNodeList resultTotal = ((XmlElement)results[0]).GetElementsByTagName("total"); //取得总得分 ArrayList Dimensions = new ArrayList(); for (int i = 0; i < resultList.Count; i++) { Hashtable tmp = new Hashtable(); System.Xml.XmlElement xe = (System.Xml.XmlElement)resultList[i]; tmp["resultName"] = xe.GetElementsByTagName("names")[0].InnerText; tmp["resultRaw"] = xe.GetElementsByTagName("raw")[0].InnerText; tmp["resultNorm"] = xe.GetElementsByTagName("norm")[0].InnerText; if (xe.ChildNodes.Count > 3) { tmp["resultLevel"] = xe.GetElementsByTagName("level")[0].InnerText; } else { tmp["resultLevel"] = "-"; } Dimensions.Add(tmp); } result["dimList"] = Dimensions; result["totalRaw"] = ((XmlElement)(resultTotal[0])).GetElementsByTagName("raw")[0].InnerText; result["totalNorm"] = ((XmlElement)(resultTotal[0])).GetElementsByTagName("norm")[0].InnerText; } catch (Exception ex) { System.Diagnostics.Debug.Write("解析课程返回数据时出错:" + ex.Message + "\n"); } return(result); }