private static void UpdateTile(List <VITask> feed) { // Create a tile update manager for the specified syndication feed. var updater = TileUpdateManager.CreateTileUpdaterForApplication(); updater.EnableNotificationQueue(true); updater.Clear(); // Keep track of the number feed items that get tile notifications. int itemCount = 0; // Create a tile notification for each feed item. foreach (var item in feed.Take(3)) { XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare310x310TextList03); tileXml.GetElementById("1").InnerText = item.CaseNumber; tileXml.GetElementById("2").InnerText = item.Customer; // Create a new tile notification. updater.Update(new TileNotification(tileXml)); } }
public void findById(String Id) { XmlElement id = doc.GetElementById(Id); if (id == null) { throw (new Exception("Not found any Id!\n")); } Console.Write(id.InnerXml + "\n" + "----------------------\n\n"); }
internal static XmlElement DefaultGetIdElement(XmlDocument document, string idValue) { if (document == null) { return(null); } try { XmlConvert.VerifyNCName(idValue); } catch (XmlException) { return(null); } XmlElement elem = document.GetElementById(idValue); if (elem != null) { XmlDocument docClone = (XmlDocument)document.CloneNode(true); XmlElement cloneElem = docClone.GetElementById(idValue); System.Diagnostics.Debug.Assert(cloneElem != null); if (cloneElem != null) { cloneElem.Attributes.RemoveAll(); XmlElement cloneElem2 = docClone.GetElementById(idValue); if (cloneElem2 != null) { throw new System.Security.Cryptography.CryptographicException( SR.Cryptography_Xml_InvalidReference); } } return(elem); } elem = CheckSignatureManager.GetSingleReferenceTarget(document, "Id", idValue); if (elem != null) { return(elem); } elem = CheckSignatureManager.GetSingleReferenceTarget(document, "id", idValue); if (elem != null) { return(elem); } elem = CheckSignatureManager.GetSingleReferenceTarget(document, "ID", idValue); return(elem); }
/// <summary> /// Parse an Xml document and validate that it has the correct structure, attributes and elements as defined by the business requirements. /// </summary> /// <param name="xmlDocument"></param> /// <returns></returns> public DocumentParseResult ValidateDocument(XmlDocument xmlDocument) { // try { // Verify that the document structure is correct. XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add("", new XmlTextReader("../Core/InputDocumentSchema.xsd")); xmlDocument.Validate(InputDocumentValidationEventHandler); // need to use the output from this if (xmlDocument.FirstChild.InnerText != "InputDocument") { return(new DocumentParseResult() { Status = -5, Message = "Invalid document structure" }); } // Check question part b // Verify that the Declaration element has the correct Command attribute if (xmlDocument.GetElementById("Declaration").HasAttribute("Command") && xmlDocument.GetElementById("Declaration").GetAttribute("Command") != "DEFAULT") { return(new DocumentParseResult() { Status = -1, Message = "Invalid command specified" }); } // Check question part c // Verify that the Site ID element has the correct Value if (xmlDocument.GetElementById("SiteID").InnerText != "DUB") { return(new DocumentParseResult() { Status = -2, Message = "Invalid site specified" }); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(new DocumentParseResult() { Status = 0, Message = "Document is structured correctly" }); }
public static void AppendDocumentXml(int id, int level, int parentId, XmlNode docXml, XmlDocument xmlContentCopy) { // Validate schema (that a definition of the current document type exists in the DTD if (!UmbracoSettings.UseLegacyXmlSchema) { ValidateSchema(docXml.Name, xmlContentCopy); } // Find the document in the xml cache XmlNode x = xmlContentCopy.GetElementById(id.ToString()); // Find the parent (used for sortering and maybe creation of new node) XmlNode parentNode; if (level == 1) { parentNode = xmlContentCopy.DocumentElement; } else { parentNode = xmlContentCopy.GetElementById(parentId.ToString()); } if (parentNode != null) { if (x == null) { x = docXml; parentNode.AppendChild(x); } else { TransferValuesFromDocumentXmlToPublishedXml(docXml, x); } // TODO: Update with new schema! string xpath = UmbracoSettings.UseLegacyXmlSchema ? "./node" : "./* [@id]"; XmlNodeList childNodes = parentNode.SelectNodes(xpath); // Maybe sort the nodes if the added node has a lower sortorder than the last if (childNodes.Count > 0) { int siblingSortOrder = int.Parse(childNodes[childNodes.Count - 1].Attributes.GetNamedItem("sortOrder").Value); int currentSortOrder = int.Parse(x.Attributes.GetNamedItem("sortOrder").Value); if (childNodes.Count > 1 && siblingSortOrder > currentSortOrder) { SortNodes(ref parentNode); } } } }
private void parserUpdateInfo() { XmlDocument updateInfoXml = new XmlDocument(); updateInfoXml.Load(UpdateInfoXMLPath); XmlElement latestVersionInfo = updateInfoXml.GetElementById("LatestVersion"); string versionNumber = latestVersionInfo.GetAttribute("Number"); string downloadUrl = latestVersionInfo.GetAttribute("DownloadURL"); string informationUrl = latestVersionInfo.GetAttribute("InformationURL"); string description = latestVersionInfo.GetAttribute("Description"); XmlElement unsupportedVersionInfo = updateInfoXml.GetElementById("UnsupportedVersion"); string unsupportedVersionNumber = unsupportedVersionInfo.GetAttribute("Number"); string unsupportedInformationUrl = unsupportedVersionInfo.GetAttribute("InformationURL"); string unsupportedDescription = unsupportedVersionInfo.GetAttribute("Description"); string currentVersionNumber = App.ResourceAssembly.GetName().Version.ToString(); if (string.Compare(currentVersionNumber, unsupportedVersionNumber) <= 0) { System.Windows.MessageBox.Show("你正在使用一个被弃用的版本,请立即更新!\n" + unsupportedDescription, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); System.Diagnostics.Process.Start(unsupportedInformationUrl); App.Current.Dispatcher.Invoke(new Action(delegate { App.Current.Shutdown(); }), null); return; } if (string.Compare(currentVersionNumber, versionNumber) < 0) { NewVersion = versionNumber; if (NewVersion == cachedUpdateVersion) { updateStatus(UpdaterStatus.ReadyToUpdate); } else { updateInfo = new UpdateInfo(); updateInfo.VersionNumber = versionNumber; updateInfo.DownloadUrl = downloadUrl; updateInfo.InformationUrl = informationUrl; updateInfo.Description = description; downloadUpdate(); } return; } else { updateStatus(UpdaterStatus.IsUpToDate); return; } }
/// <summary> /// Submit the form on the Agile Automation's website, asynchronously. /// </summary> /// <param name="formData">An object that holds the data necessary to submit the form.</param> /// <returns>A deferred task that will produce a string reference number, tied to a unique submission.</returns> /// <seealso cref="MyXmlException"/> /// <seealso cref="WebException"/> /// <seealso cref="InvalidReferenceException"/> public static async Task <string> PostFormDataAsync(FormData formData) { string reference = string.Empty; string xmlString = string.Empty; string formUrl = "https://agileautomations.co.uk/home/inputform"; XmlDocument document; HttpWebRequest postRequest; HttpWebResponse formResponse; Stream stream; StreamReader reader; postRequest = (HttpWebRequest)WebRequest.Create(formUrl); postRequest.Headers.Add("ContactName", formData.ContactName); postRequest.Headers.Add("ContactEmail", formData.ContactEmail); postRequest.Headers.Add("ContactSubject", formData.ContactSubject); postRequest.Headers.Add("Message", formData.Message); postRequest.Headers.Add("ReferenceNo", ""); postRequest.ContentType = "multipart/form-data"; postRequest.Accept = "text/*"; formResponse = (HttpWebResponse)await postRequest.GetResponseAsync(); stream = formResponse.GetResponseStream(); document = new XmlDocument(); reader = new StreamReader(stream); try { xmlString = reader.ReadToEnd(); document.LoadXml(xmlString); reference = document.GetElementById("ReferenceNo").InnerText; } catch (XmlException e) { // Try a fallback method in case previous method fails. Regex referenceFinder = new Regex(@"<label id=ReferenceNo>([^<>]*)<\/label>"); // find the right element Match match = referenceFinder.Match(xmlString); if (match.Success) { reference = match.Groups[0].Value; } else { throw new MyXmlException("Failed to parse the response upon submitting the form.", e, xmlString); } } catch (WebException e) { if (document == null) { throw new WebException($"A network error has ocurred Web response status code was {formResponse.StatusCode} and description: {formResponse.StatusDescription}", e); } } if (!ReferenceValid(reference)) { throw new InvalidReferenceException("Reference - 1234567", reference); } return(reference); }
// This function expands the overriden GetIdElement method of the // base SignedXML class to search for attribute "id" in addition to // the default "Id" attribute. public override XmlElement GetIdElement(XmlDocument document, string idValue) { if (document == null) { return(null); } // Get the element with idValue XmlElement elem = document.GetElementById(idValue); if (elem != null) { return(elem); } // Make a list of the possible id's since it is case sensitive. string[] arraySearchIDs = { "id", "Id", "ID", "wsu:id", "wsu:Id", "wsu:ID", "WSU:id", "WSU:Id", "WSU:ID" }; // search with namespace wsu // http://stackoverflow.com/questions/5099156/malformed-reference-element-when-adding-a-reference-based-on-an-id-attribute-w XmlNamespaceManager nsManager = new XmlNamespaceManager(document.NameTable); nsManager.AddNamespace("wsu", CustomSignedXml.xmlOasisWSSSecurityUtilUrl); foreach (string idLabel in arraySearchIDs) { // Get the element with idValue, try all combinations in array string xpathId = "//*[@" + idLabel + "=\"" + idValue + "\"]"; elem = document.SelectSingleNode(xpathId, nsManager) as XmlElement; if (elem != null) { return(elem); } } return(elem); }
public virtual XmlElement GetIdElement(XmlDocument document, string idValue) { if ((document == null) || (idValue == null)) { return(null); } // this works only if there's a DTD or XSD available to define the ID XmlElement xel = document.GetElementById(idValue); if (xel == null) { // search an "undefined" ID xel = (XmlElement)document.SelectSingleNode("//*[@Id='" + idValue + "']"); if (xel == null) { xel = (XmlElement)document.SelectSingleNode("//*[@ID='" + idValue + "']"); if (xel == null) { xel = (XmlElement)document.SelectSingleNode("//*[@id='" + idValue + "']"); } } } return(xel); }
// // public virtual methods // // This describes how the application wants to associate id references to elements public virtual XmlElement GetIdElement(XmlDocument document, string idValue) { if (document == null) { return(null); } XmlElement elem = null; // Get the element with idValue elem = document.GetElementById(idValue); if (elem != null) { return(elem); } elem = document.SelectSingleNode("//*[@Id=\"" + idValue + "\"]") as XmlElement; if (elem != null) { return(elem); } elem = document.SelectSingleNode("//*[@id=\"" + idValue + "\"]") as XmlElement; if (elem != null) { return(elem); } elem = document.SelectSingleNode("//*[@ID=\"" + idValue + "\"]") as XmlElement; return(elem); }
public void Sort_Nodes() { var xmlContent = GetXmlContent(1); var xml = new XmlDocument(); xml.LoadXml(xmlContent); var original = xml.GetElementById(1173.ToString()); Assert.IsNotNull(original); var parentNode = (XmlElement)original.Clone(); XmlHelper.SortNodes( parentNode, "./* [@id]", x => x.AttributeValue <int>("sortOrder")); //do assertions just to make sure it is working properly. var currSort = 0; foreach (var child in parentNode.SelectNodes("./* [@id]").Cast <XmlNode>()) { Assert.AreEqual(currSort, int.Parse(child.Attributes["sortOrder"].Value)); currSort++; } //ensure the parent node's properties still exist first Assert.AreEqual("content", parentNode.ChildNodes[0].Name); Assert.AreEqual("umbracoUrlAlias", parentNode.ChildNodes[1].Name); //then the child nodes should come straight after Assert.IsTrue(parentNode.ChildNodes[2].Attributes["id"] != null); }
public static XmlElement GetElementById(string xml, string elementId) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); return(doc.GetElementById(elementId)); }
public void SaveRithmicInstruments() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("rithmic.xml"); XmlElement documentElement = xmlDocument.DocumentElement; documentElement.InnerXml = ""; foreach (Settings.rithmicSubscription rithmicSubscription in this.rithmicSubscriptions) { string exchange = rithmicSubscription.exchange; string symbol = rithmicSubscription.symbol; XmlElement xmlElement = xmlDocument.GetElementById(exchange); if (xmlElement == null) { xmlElement = xmlDocument.CreateElement("exchange"); xmlElement.SetAttribute("id", exchange); documentElement.AppendChild((XmlNode)xmlElement); } XmlElement element = xmlDocument.CreateElement("symbol"); element.InnerText = symbol; xmlElement.AppendChild((XmlNode)element); } xmlDocument.Save("rithmic.xml"); }
public DialogueNode GetDialogueNode(string id) { XmlElement node = CurrentDialogXML.GetElementById(id); if (node == null) { return(null); } XmlNodeList nodeContent = node.ChildNodes; DialogueNode dialogueNode = new DialogueNode(); foreach (XmlNode nodeItem in nodeContent) { if (nodeItem.Name == "response") { DialogueResponse response = GetDialogueResponse(nodeItem); dialogueNode.Responses.Add(response); } else if (nodeItem.Name == "option") { Topic option = GetDialogueOption(nodeItem); dialogueNode.Options.Add(option); } } return(dialogueNode); }
public void addAnswersToXML() { XmlDocument doc = currentUser.newTest.sourceFile; int c = currentUser.newTest.questions.Count; for (int i = 0; i < c; i++) { Question q = currentUser.newTest.questions[i]; int qID = q.id; XmlNode insertNode = doc.GetElementById(qID.ToString()); if (q.userAnswerList != null) { foreach (Answer a in q.userAnswerList) { XmlElement userAnswer = doc.CreateElement("userAnswer"); XmlAttribute attr = doc.CreateAttribute("ID"); attr.Value = a.id.ToString(); userAnswer.Attributes.Append(attr); insertNode.AppendChild(userAnswer); } } } currentUser.newTest.sourceFile = doc; }
Mesh GenetareFlor() { TextAsset xml = AssetDatabase.LoadAssetAtPath <TextAsset>("Assets/Resources/Levels/level_s0_e14.xml"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml.text); var root = xmlDoc.GetElementById("grid"); var geometry = xmlDoc.GetElementsByTagName("geometry").Item(0); var playerNode = xmlDoc.GetElementsByTagName("object").Item(0); var pCols = playerNode.Attributes.GetNamedItem("col").Value; int pCol = 0; int.TryParse(pCols, out pCol); var pRows = playerNode.Attributes.GetNamedItem("row").Value; int pRow = 0; int.TryParse(pRows, out pRow); player.transform.position = new Vector3(pCol, 1, pRow); Mesh mesh = new Mesh(); var quads = new List <Quad>(); foreach (var child in geometry.ChildNodes) { var item = child as XmlElement; if (item == null) { break; } quads.Add(new Quad(item)); } var vertices = quads.SelectMany(x => x.Vertices).ToList(); var normals = quads.SelectMany(x => x.Normals).ToList(); var indices = new List <int>(); for (int i = 0; i < quads.Count; i++) { indices.AddRange(new int[] { 0, 1, 2, 3, 4, 5 }.Select(x => x + i * 6).ToArray()); } vertices.Select(x => vertices.IndexOf(x)).ToList(); var uvs = quads.SelectMany(x => x.UVs).ToList(); mesh.SetVertices(vertices); mesh.SetTriangles(indices, 0); mesh.SetNormals(normals); mesh.SetUVs(0, uvs); return(mesh); }
public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("ids.xml"); //Get the first element with an attribute of type ID and value of A111. //This displays the node <Person SSN="A111" Name="Fred"/>. XmlElement elem = doc.GetElementById("A111"); Console.WriteLine(elem.OuterXml); //Get the first element with an attribute of type ID and value of A222. //This displays the node <Person SSN="A222" Name="Tom"/>. elem = doc.GetElementById("A222"); Console.WriteLine(elem.OuterXml); }
private void ReadXml() { XmlDocument document = new XmlDocument(); document.Load(filename + ".xml"); XmlElement element = document.GetElementById("Database"); current = uint.Parse(element.Value); }
/// <summary> /// Clears the document cache and removes the document from the xml db cache. /// This means the node gets unpublished from the website. /// </summary> /// <param name="documentId">The document id.</param> public virtual void ClearDocumentCache(int documentId) { // Get the document Document d = new Document(documentId); cms.businesslogic.DocumentCacheEventArgs e = new umbraco.cms.businesslogic.DocumentCacheEventArgs(); FireBeforeClearDocumentCache(d, e); if (!e.Cancel) { XmlNode x; // remove from xml db cache d.XmlRemoveFromDB(); // Check if node present, before cloning x = XmlContentInternal.GetElementById(d.Id.ToString()); if (x == null) { return; } // We need to lock content cache here, because we cannot allow other threads // making changes at the same time, they need to be queued lock (_xmlContentInternalSyncLock) { // Make copy of memory content, we cannot make changes to the same document // the is read from elsewhere XmlDocument xmlContentCopy = CloneXmlDoc(XmlContentInternal); // Find the document in the xml cache x = xmlContentCopy.GetElementById(d.Id.ToString()); if (x != null) { // The document already exists in cache, so repopulate it x.ParentNode.RemoveChild(x); XmlContentInternal = xmlContentCopy; ClearContextCache(); } } if (x != null) { // Run Handler umbraco.BusinessLogic.Actions.Action.RunActionHandlers(d, ActionUnPublish.Instance); } // update sitemapprovider if (SiteMap.Provider is presentation.nodeFactory.UmbracoSiteMapProvider) { presentation.nodeFactory.UmbracoSiteMapProvider prov = (presentation.nodeFactory.UmbracoSiteMapProvider)SiteMap.Provider; prov.RemoveNode(d.Id); } FireAfterClearDocumentCache(d, e); } }
public static string XmlToJson(string xml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc.GetElementById("xml")); return(json); }
private void button1_Click(object sender, EventArgs e) { XmlElement ele = doc.GetElementById(comboBox1.SelectedItem.ToString()); label6.Text = ele.ChildNodes[0].InnerText; label7.Text = ele.ChildNodes[1].InnerText; label8.Text = ele.ChildNodes[2].InnerText; label9.Text = ele.ChildNodes[3].InnerText; }
static void Search() { XmlDocument xDoc = new XmlDocument(); FileStream myFile = new FileStream("../cities.xml", FileMode.Open); xDoc.Load(myFile); //1 XmlNodeList names = xDoc.GetElementsByTagName("City"); for (int i = 0; i < names.Count; i++) { Console.Write(names[i].ChildNodes[0].Value + "\r\n"); } //2 XmlDocument xDoc1 = new XmlDocument(); FileStream myFile1 = new FileStream("../citiesW.xml", FileMode.Open); xDoc1.Load(myFile1); Console.WriteLine("ID to find: "); string ID_find = Console.ReadLine(); XmlElement id = xDoc1.GetElementById(ID_find); if (id == null) { Console.Write("NULL"); Console.Write(id); } else { Console.Write(id.ChildNodes[0].InnerText + "\r\n"); } //3 XmlNodeList sur = xDoc.SelectNodes("//row/City/text()[../City_id/text()<'5']"); for (int i = 0; i < sur.Count; i++) { Console.Write("\nSelect Nodes_1: " + sur[i].Value + "\r\n"); } XmlNodeList second = xDoc.SelectNodes("descendant::row[City_id = 5]"); for (int i = 0; i < second.Count; i++) { Console.Write("\nSelect Nodes_2: " + second[i].ChildNodes[1].ChildNodes[0].Value + "\r\n"); } //4 XmlNode single = xDoc.SelectSingleNode("descendant::row[City_id < 5]"); Console.Write("\nSelect Single: " + single.ChildNodes[1].ChildNodes[0].Value + "\r\n"); myFile.Close(); myFile1.Close(); }
public void LoadXML(string ID) { if (xmlLevelFile != null) { XmlDocument root = new XmlDocument(); root.LoadXml(xmlLevelFile.text); XmlElement elem = root.GetElementById(ID); levelData = new LevelData(); levelData.star1 = float.Parse(elem.Attributes["star1"].Value); levelData.star2 = float.Parse(elem.Attributes["star2"].Value); levelData.star3 = float.Parse(elem.Attributes["star3"].Value); foreach (XmlNode k in elem.ChildNodes) { Tumbler t = new Tumbler(); t.ID = k.Attributes["ID"].Value; t.x = float.Parse(k.Attributes["x"].Value); t.slotY = float.Parse(k.FirstChild.Attributes["y"].Value); XmlNode c = k.LastChild; t.bottomY = float.Parse(c.PreviousSibling.Attributes["y"].Value); t.bottomScale = int.Parse(c.PreviousSibling.Attributes["scale"].Value); t.bottomWeight = int.Parse(c.PreviousSibling.Attributes["weight"].Value); t.topY = float.Parse(c.Attributes["y"].Value); t.topFall = int.Parse(c.Attributes["fall"].Value); levelData.tumblers.Add(t); } foreach (string l in f1) { if (ID == "L_" + l) { chamberColor = new Color32(59, 174, 218, 255); levelSelectExitCode = 0; } } foreach (string l in f2) { if (ID == "L_" + l) { chamberColor = new Color32(40, 185, 94, 255); levelSelectExitCode = 1; } } foreach (string l in f3) { if (ID == "L_" + l) { chamberColor = new Color32(232, 121, 0, 255); levelSelectExitCode = 2; } } levelData.ID = ID; SceneManager.LoadScene("Arena"); } }
public int getXMLInfo() { XmlNodeList tagList = doc.GetElementsByTagName("id"); Console.WriteLine(); int t_count = tagList.Count; int choose = get_int("Введите id тайтла (Доступны от 1 до " + t_count + ")", 1, t_count, "Попробуем еще раз. Если хотите выйти введите число меньше 0"); if (choose == INPUT_INT_ERROR) { return(NOERROR); } XmlElement id = doc.GetElementById(tagList[choose - 1].Attributes[0].InnerText); allAboutXmlElement(id, 0); Console.WriteLine(); Console.WriteLine("'Сырой' xml данного тайтла:" + id.InnerXml); XmlNode x = doc.SelectSingleNode("/root"); if (x == null) { return(NO_ROOT); } Console.WriteLine(); Console.WriteLine("Спрятанные комментарии:"); allAboutXmlElementComments(id); Console.WriteLine(); Console.WriteLine("Инструкции:"); XmlProcessingInstruction instruction = doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction; if (instruction == null) { return(NO_INSTRUCTION); } Console.WriteLine(instruction.InnerText); return(NOERROR); }
public static bool saveCheck(string str) { try { XmlDocument doc = new XmlDocument(); doc.Load(@"user.xml"); XmlElement node = doc.GetElementById("user"); XmlNode check = (XmlNode)doc.GetElementById("check"); check.InnerText = str; //node.AppendChild(check); //doc.DocumentElement.InsertAfter(node, doc.DocumentElement.LastChild); doc.Save(@"user.xml"); } catch (Exception exp) { return(false); } return(true); }
public SplashKitAdapter() { _config = new XmlDocument(); _config.Load("config.xml"); int numPlayers = Convert.ToInt32(_config.GetElementById("players").Attributes["num"].Value); _controls = new Dictionary <ControlType, KeyCode> [numPlayers]; for (int i = 0; i < _controls.Length; i++) { _controls[i] = new Dictionary <ControlType, KeyCode>(); XmlNodeList controls = _config.GetElementById(i.ToString()).GetElementsByTagName("control"); foreach (XmlNode control in controls) { ControlType type = Enum.Parse <ControlType>(control.Attributes["type"].Value); KeyCode key = Enum.Parse <KeyCode>(control.Attributes["key"].Value); _controls[i].Add(type, key); } } }
public virtual FilterGraph readFilterGraph(XmlDocument doc) { FilterGraph result = null; if (doc != null) { result = decodeFilterGraph(doc.GetElementById("graph"), null); } return(result); }
public static void QueryXml0() { XmlDocument doc = new XmlDocument(); string xml = Resources.Person; doc.LoadXml(xml); XmlElement elem = doc.GetElementById("A111"); if (elem != null) { Console.WriteLine(elem.OuterXml); } elem = doc.GetElementById("A222"); if (elem != null) { Console.WriteLine(elem.OuterXml); } }
private int GetPageCount() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(GameManager.BOOK_PATH); XmlNode bookNode = xmlDoc.GetElementById(bookId); int pageCount = bookNode.ChildNodes.Count; return(pageCount); }
/// <summary> /// /// </summary> /// <param name="umbPage"></param> /// <param name="attributes"></param> /// public item(IDictionary elements, IDictionary attributes) { _fieldName = helper.FindAttribute(attributes, "field"); if (_fieldName.StartsWith("#")) { _fieldContent = library.GetDictionaryItem(_fieldName.Substring(1, _fieldName.Length - 1)); } else { // Loop through XML children we need to find the fields recursive if (helper.FindAttribute(attributes, "recursive") == "true") { XmlDocument umbracoXML = presentation.UmbracoContext.Current.GetXml(); String[] splitpath = (String[])elements["splitpath"]; for (int i = 0; i < splitpath.Length - 1; i++) { XmlNode element = umbracoXML.GetElementById(splitpath[splitpath.Length - i - 1].ToString()); if (element == null) { continue; } string xpath = UmbracoSettings.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "./{0}"; XmlNode currentNode = element.SelectSingleNode(string.Format(xpath, _fieldName)); if (currentNode != null && currentNode.FirstChild != null && !string.IsNullOrEmpty(currentNode.FirstChild.Value) && !string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim())) { HttpContext.Current.Trace.Write("item.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]); _fieldContent = currentNode.FirstChild.Value; break; } } } else { if (elements[_fieldName] != null && !string.IsNullOrEmpty(elements[_fieldName].ToString())) { _fieldContent = elements[_fieldName].ToString().Trim(); } else if (!string.IsNullOrEmpty(helper.FindAttribute(attributes, "useIfEmpty"))) { if (elements[helper.FindAttribute(attributes, "useIfEmpty")] != null && !string.IsNullOrEmpty(elements[helper.FindAttribute(attributes, "useIfEmpty")].ToString())) { _fieldContent = elements[helper.FindAttribute(attributes, "useIfEmpty")].ToString().Trim(); } } } } parseItem(attributes); }
public DataTable GetTranslationTable(string languageFilePath, string sourceLanguage, string targetLanguage) { DataTable LanguageTbl = new DataTable(); string SrcLanguageFileName = string.Empty; string TrgLanguagefileName = string.Empty; string Key = string.Empty; string SourceValue = string.Empty; string TargetValue = string.Empty; LanguageTbl = CreateLanguageTable(); SrcLanguageFileName = languageFilePath + sourceLanguage + ".xml"; TrgLanguagefileName = languageFilePath + targetLanguage + ".xml"; XmlDocument xmlDocSource = new XmlDocument(); xmlDocSource.Load(SrcLanguageFileName); XmlNodeList xmlNodeList = xmlDocSource.SelectNodes("root/Row"); XmlDocument xmlDocTarget = new XmlDocument(); xmlDocTarget.Load(TrgLanguagefileName); XmlElement Element; foreach (XmlNode xmlNode in xmlNodeList) { Key = xmlNode.Attributes[0].Value; SourceValue = xmlNode.Attributes[1].Value; //Find key value in target language file. Element = xmlDocTarget.GetElementById(Key); try { TargetValue = Element.Attributes["value"].Value; } catch (Exception ex) { TargetValue = ""; Global.CreateExceptionString(ex, null); } InsertDataIntoLanguageTbl(Key, SourceValue, TargetValue, LanguageTbl); } return LanguageTbl; }
public void GenarateGrid(string Type ,float Difficalt) { // Background = Instantiate(Resources.Load("Prefab/Forest"), new Vector3(0, 2.5f, 0), Quaternion.identity) as GameObject; _Background = Camera.main.transform.FindChild("Background").GetComponent<Background>(); // float Rand = 0f; //Рандомная величина GameObject Now; //Переменная для поиска спаунящегося блока TextAsset xmlAsset = Resources.Load("LevelStats/" + Type) as TextAsset; //Считываня xml XmlDocument xmlDoc = new XmlDocument(); if (xmlAsset) xmlDoc.LoadXml(xmlAsset.text); XmlElement Stats = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("Location"); Height = Convert.ToInt16(Stats.GetAttribute("height")); Widht = Convert.ToInt16(Stats.GetAttribute("width")); int CountBack = Convert.ToInt16(xmlDoc.DocumentElement.SelectSingleNode("//Background").Attributes[0].Value); //string Str = ; _Background.SetUpBackGround(Resources.Load<Sprite>("Sprites/Back/" + Type + "/" + UnityEngine.Random.Range(1, CountBack + 1))); List<Vector2> TreesCoords = new List<Vector2>(); int IndentTree = Convert.ToInt16(xmlDoc.DocumentElement.SelectSingleNode("//Tree").Attributes[0].Value); BlockGrid = new Block[Height + 2, Widht]; // BlockGrid[0, 30] = new Block(); XmlElement Lvl = xmlDoc.GetElementById("1"); for (int i = -1; i <= Height; i++) { for (int x = -Widht / 2; x <= Widht / 2 - 1; x++) { Rand = UnityEngine.Random.value; switch (i) { case -1: if (UnityEngine.Random.value < Convert.ToSingle(xmlDoc.DocumentElement.SelectSingleNode("//Tree").Attributes[1].Value)) { if (x <= 0) { if (TreesCoords.Count > 0) { if (TreesCoords[TreesCoords.Count - 1].x + IndentTree <= x) TreesCoords.Add(new Vector2(x, 1)); } else TreesCoords.Add(new Vector2(x, 1)); } else { if (UnityEngine.Random.value < 0.5f) if (TreesCoords.Count > 0) { if (TreesCoords[TreesCoords.Count - 1].x + IndentTree <= x) TreesCoords.Add(new Vector2(x, 1)); } else TreesCoords.Add(new Vector2(x, 1)); } } break; case 0: Now = Instantiate(Resources.Load("Prefab/GroundUp"), new Vector3(x, -i, 0), Quaternion.identity) as GameObject; BlockGrid[i, x + 15] = Now.GetComponent<Ground>(); BlockGrid[i, (x + 15)].gameObject.transform.parent = this.gameObject.transform; break; default: if (UnityEngine.Random.value <= Difficalt) { if (!BlockGrid[i, x + 15]) { Now = Instantiate(Resources.Load("Prefab/Ground"), new Vector3(x, -i, 0), Quaternion.identity) as GameObject; BlockGrid[i, x + 15] = Now.GetComponent<Ground>(); BlockGrid[i, (x + 15)].gameObject.transform.parent = this.gameObject.transform; } } else { bool Spawn = false; XmlNodeList dataList = xmlDoc.GetElementsByTagName("level")[0].ChildNodes; for (int j = 0; j < dataList.Count; j++) { string[] substrings = Regex.Split(dataList[j].Attributes[1].Value, "(-)"); if (i >= Convert.ToInt16(substrings[0]) && i <= Convert.ToInt16(substrings[2])) { Rand = UnityEngine.Random.value; if (Rand <= Convert.ToSingle(dataList[j].Attributes[0].Value) && !BlockGrid[i, x + 15]) { if (!BlockGrid[i, x + 15]) GenerateResourse(i, x, dataList[j].Attributes[2].Value, dataList[j].Name); Spawn = true; break; } } } if (!Spawn) { if (!BlockGrid[i, x + 15]) { Now = Instantiate(Resources.Load("Prefab/Ground"), new Vector3(x, -i, 0), Quaternion.identity) as GameObject; BlockGrid[i, x + 15] = Now.GetComponent<Ground>(); BlockGrid[i, (x + 15)].gameObject.transform.parent = this.gameObject.transform; } } } break; } } } for (int i = 0; i <= Height; i++) { for (int x = -Widht / 2; x <= Widht / 2 - 1; x++) { if (!BlockGrid[i, x + 15]) { Now = Instantiate(Resources.Load("Prefab/Ground"), new Vector3(x, -i, 0), Quaternion.identity) as GameObject; BlockGrid[i, x + 15] = Now.GetComponent<Ground>(); BlockGrid[i, (x + 15)].gameObject.transform.parent = this.gameObject.transform; } } } GenerateTree(TreesCoords); GenerateZone(); _Background.gameObject.SetActive(true); }
/* * Use * string unitString must contain .xml at the end, otherwise Load won't find the file */ public Unit Load(string unitString) { filePath = "Assets/Units/"; xFile = new XmlDocument(); xFile.Load(filePath + unitString); // Start reading the file and pulling data out of it Unit unit = new Unit(); unit.Name = xFile.GetElementById("name").InnerText; unit.type = xFile.GetElementById("type").InnerText; unit.lifepoints = int.Parse(xFile.GetElementById("hp").InnerText); // TODO: fix lifepoints versus hp, might create confusion unit.damage = int.Parse(xFile.GetElementById("dmg").InnerText); unit.hull = int.Parse( xFile.GetElementById("hull").InnerText); unit.price = int.Parse(xFile.GetElementById("price").InnerText); unit.productionTime = int.Parse(xFile.GetElementById("productiontime").InnerText); return unit; }