internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) { this.attr = attr; this.o = o; this.qnames = qnames; this.lineNumber = lineNumber; this.linePosition = linePosition; }
// Check the properties on an attribute. private void CheckProperties(String msg, XmlAttribute attr, String prefix, String name, String ns, String value) { XmlNameTable nt = doc.NameTable; prefix = nt.Add(prefix); name = nt.Add(name); ns = nt.Add(ns); AssertSame(msg + " [1]", prefix, attr.Prefix); AssertSame(msg + " [2]", name, attr.LocalName); AssertSame(msg + " [3]", ns, attr.NamespaceURI); if(prefix != String.Empty) { String combined = nt.Add(prefix + ":" + name); AssertEquals(msg + " [4]", combined, attr.Name); } else { AssertSame(msg + " [5]", name, attr.Name); } AssertEquals(msg + " [6]", XmlNodeType.Attribute, attr.NodeType); AssertEquals(msg + " [7]", doc, attr.OwnerDocument); AssertNull(msg + " [8]", attr.OwnerElement); AssertNull(msg + " [9]", attr.ParentNode); AssertEquals(msg + " [10]", value, attr.InnerText); AssertEquals(msg + " [11]", value, attr.Value); Assert(msg + " [12]", attr.Specified); }
internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) { _attr = attr; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; }
public static int FindNodeOffsetNS(this XmlAttributeCollection collection, XmlAttribute node) { for (int i = 0; i < collection.Count; i++) { XmlAttribute tmp = collection[i]; if (tmp.LocalName == node.LocalName && tmp.NamespaceURI == node.NamespaceURI) { return i; } } return -1; }
public void CopyToCopiesReferences() { XmlDocument doc = CreateDocumentWithElement(); XmlElement element = doc.DocumentElement; XmlAttribute attr1, attr2, attr3; attr1 = element.Attributes.Append(doc.CreateAttribute("attr1")); attr2 = element.Attributes.Append(doc.CreateAttribute("attr2")); attr3 = element.Attributes.Append(doc.CreateAttribute("attr3")); XmlAttribute[] destinationArray = new XmlAttribute[3]; ICollection target = element.Attributes; target.CopyTo(destinationArray, 0); Assert.Same(attr1, destinationArray[0]); Assert.Same(attr2, destinationArray[1]); Assert.Same(attr3, destinationArray[2]); }
public void CopyToCopiesClonedAttributesAtSpecifiedLocation() { XmlDocument doc = CreateDocumentWithElement(); XmlElement element = doc.DocumentElement; XmlAttribute attr1, attr2; attr1 = element.Attributes.Append(doc.CreateAttribute("attr1")); attr2 = element.Attributes.Append(doc.CreateAttribute("attr2")); XmlAttribute[] destinationArray = new XmlAttribute[4]; XmlAttributeCollection target = element.Attributes; target.CopyTo(destinationArray, 2); Assert.Null(destinationArray[0]); Assert.Null(destinationArray[1]); Assert.NotNull(destinationArray[2]); Assert.NotNull(destinationArray[3]); }
public void CopyToCopiesClonedAttributes() { XmlDocument doc = CreateDocumentWithElement(); XmlElement element = doc.DocumentElement; XmlAttribute attr1, attr2; attr1 = element.Attributes.Append(doc.CreateAttribute("attr1")); attr2 = element.Attributes.Append(doc.CreateAttribute("attr2")); XmlAttribute[] destinationArray = new XmlAttribute[2]; XmlAttributeCollection target = element.Attributes; target.CopyTo(destinationArray, 0); Assert.NotNull(destinationArray[0]); Assert.NotSame(attr1, destinationArray[0]); Assert.NotSame(element, destinationArray[0].OwnerElement); Assert.Equal("attr1", destinationArray[0].LocalName); Assert.NotNull(destinationArray[1]); Assert.NotSame(attr2, destinationArray[1]); Assert.NotSame(element, destinationArray[1].OwnerElement); Assert.Equal("attr2", destinationArray[1].LocalName); }
private void doUpgrade(Version version) { if (version.CompareTo(Version.Parse("7.1")) == -1) {//Perform v7.0 to v7.1 upgrade doc.SelectSingleNode("/hapConfig/myfiles").Attributes["hideextensions"].Value = doc.SelectSingleNode("/hapConfig/myfiles").Attributes["hideextensions"].Value.Replace(';', ','); } if (version.CompareTo(Version.Parse("7.3")) == -1) {//Perform v7.3 upgrade if (doc.SelectSingleNode("/hapConfig/Homepage/Links/Group/Link[@name='Browse My School Computer']") != null) { doc.SelectSingleNode("/hapConfig/Homepage/Links/Group/Link[@name='Browse My School Computer']").Attributes["name"].Value = "My School Files"; } if (doc.SelectSingleNode("/hapConfig/Homepage/Links/Group/Link[@name='Access a School Computer']") != null) { doc.SelectSingleNode("/hapConfig/Homepage/Links/Group/Link[@name='Access a School Computer']").Attributes["name"].Value = "Remote Apps"; } if (doc.SelectSingleNode("/hapConfig/Homepage/Links/Group/Link[@name='RM Management Console']") != null) { doc.SelectSingleNode("/hapConfig/Homepage/Links/Group/Link[@name='RM Management Console']").Attributes["name"].Value = "RM Console"; } } if (version.CompareTo(Version.Parse("7.4")) == -1) {//Perform v7.4 upgrade foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group")) { XmlAttribute a = doc.CreateAttribute("subtitle"); a.Value = ""; n.Attributes.Append(a); } } if (version.CompareTo(Version.Parse("7.7")) < 0) {//Perform v7.7 Upgrade foreach (XmlNode n in doc.SelectNodes("/hapConfig/AD/OUs/OU")) { XmlAttribute a = doc.CreateAttribute("visibility"); a.Value = bool.Parse(n.Attributes["ignore"].Value) ? OUVisibility.None.ToString() : OUVisibility.Both.ToString(); n.Attributes.Append(a); n.Attributes.Remove(n.Attributes["ignore"]); } } if (version.CompareTo(Version.Parse("7.7.1128.2200")) < 0) {//Perform v7.7 Upgrade foreach (XmlNode n in doc.SelectNodes("/hapConfig/bookingsystem/resources/resource")) { XmlAttribute a = doc.CreateAttribute("showto"); a.Value = "All"; n.Attributes.Append(a); } } if (version.CompareTo(Version.Parse("7.9.0103.1500")) < 0) {//Perform v7.9 Upgrade XmlAttribute a = doc.CreateAttribute("local"); a.Value = "en-gb"; doc.SelectSingleNode("/hapConfig").Attributes.Append(a); } if (version.CompareTo(Version.Parse("8.0.0527.1300")) < 0) {//Perform v8 Upgrade XmlAttribute a = doc.CreateAttribute("local"); a.Value = "en-gb"; doc.SelectSingleNode("/hapConfig").Attributes.Append(a); doc.SelectSingleNode("/hapConfig/Homepage").RemoveChild(doc.SelectSingleNode("/hapConfig/Homepage/Tabs")); if (doc.SelectNodes("/hapConfig/Homepage/Group[@name='Me']").Count > 0) { doc.SelectSingleNode("/hapConfig/Homepage").RemoveChild(doc.SelectSingleNode("/hapConfig/Homepage/Group[@name='Me']")); } XmlElement e = doc.CreateElement("Group"); e.SetAttribute("showto", "All"); e.SetAttribute("name", "Me"); e.SetAttribute("subtitle", "#me"); XmlElement e1 = doc.CreateElement("Link"); e1.SetAttribute("name", "Me"); e1.SetAttribute("showto", "Inherit"); e1.SetAttribute("description", ""); e1.SetAttribute("url", ""); e1.SetAttribute("icon", ""); e1.SetAttribute("target", ""); e.AppendChild(e1); e1 = doc.CreateElement("Link"); e1.SetAttribute("name", "Password"); e1.SetAttribute("showto", "Inerhit"); e1.SetAttribute("description", ""); e1.SetAttribute("url", ""); e1.SetAttribute("icon", ""); e1.SetAttribute("target", ""); e.AppendChild(e1); doc.SelectSingleNode("/hapConfig/Homepage/Links").AppendChild(e); } if (version.CompareTo(Version.Parse("8.0.0714.1945")) < 0) {//Perform v8.0714 Update foreach (XmlNode n in doc.SelectNodes("/hapConfig/bookingsystem/resources/resource")) { n.Attributes.Append(doc.CreateAttribute("hidefrom")); n.Attributes.Append(doc.CreateAttribute("years")); n.Attributes.Append(doc.CreateAttribute("quantities")); n.Attributes["hidefrom"].Value = ""; n.Attributes["quantities"].Value = ""; n.Attributes["years"].Value = "Inherit"; } } if (version.CompareTo(Version.Parse("8.0.0714.2010")) < 0) {//Perform v8.0714.2010 Update foreach (XmlNode n in doc.SelectNodes("/hapConfig/bookingsystem/resources/resource")) { n.Attributes.Append(doc.CreateAttribute("readonlyto")); n.Attributes.Append(doc.CreateAttribute("readwriteto")); n.Attributes["readwriteto"].Value = n.Attributes["readonlyto"].Value = ""; } } if (version.CompareTo(Version.Parse("8.0.0801.2359")) < 0) {//Perform v8.0.0801.2359 Update doc.SelectSingleNode("/hapConfig/bookingsystem").Attributes.Append(doc.CreateAttribute("enablemultilesson")); doc.SelectSingleNode("/hapConfig/bookingsystem").Attributes["enablemultilesson"].Value = "false"; foreach (XmlNode n in doc.SelectNodes("/hapConfig/bookingsystem/resources/resource")) { n.Attributes.Append(doc.CreateAttribute("multilessonto")); n.Attributes["multilessonto"].Value = "None"; } } if (version.CompareTo(Version.Parse("8.0.0802.2000")) < 0) {//Perform v8.0.0802.2000 Update foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link[@url='#me']")) { n.Attributes["icon"].Value = "~/images/icons/metro/folders-os/UserNo-Frame.png"; XmlAttribute a = doc.CreateAttribute("type"); a.Value = "me"; n.Attributes.Append(a); } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link[@url='~/myfiles/']")) { n.Attributes["icon"].Value = "~/images/icons/metro/folders-os/DocumentsFolder.png"; XmlAttribute a = doc.CreateAttribute("type"); a.Value = "myfiles"; n.Attributes.Append(a); } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link[@url='~/helpdesk/']")) { n.Attributes["icon"].Value = "~/images/icons/metro/folders-os/help.png"; XmlAttribute a = doc.CreateAttribute("type"); a.Value = "helpdesk"; n.Attributes.Append(a); } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link[@url='~/bookingsystem/']")) { n.Attributes["icon"].Value = "~/images/icons/metro/applications/calendar.png"; XmlAttribute a = doc.CreateAttribute("type"); a.Value = "bookings"; n.Attributes.Append(a); } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link[@url='~/tracker/']")) { n.Attributes["icon"].Value = "~/images/icons/metro/other/History.png"; } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link[@url='~/setup.aspx']")) { n.Attributes["icon"].Value = "~/images/icons/metro/folders-os/Configurealt1.png"; } } if (version.CompareTo(Version.Parse("8.5.1121.1800")) < 0)//Perform v8.5 upgrade, rename mscb to myfiles { XmlElement oldElement = (XmlElement)doc.SelectSingleNode("/hapConfig/mscb"); if (oldElement != null) { XmlElement newElement = doc.CreateElement("myfiles"); while (oldElement.HasAttributes) { newElement.SetAttributeNode(oldElement.RemoveAttributeNode(oldElement.Attributes[0])); } while (oldElement.HasChildNodes) { newElement.AppendChild(oldElement.FirstChild); } if (oldElement.ParentNode != null) { oldElement.ParentNode.ReplaceChild(newElement, oldElement); } } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group")) { XmlElement en = n as XmlElement; en.SetAttribute("hidehomepage", "False"); en.SetAttribute("hidetopmenu", "False"); en.SetAttribute("hidehomepagelink", "False"); } } if (version.CompareTo(Version.Parse("8.5.1202.0000")) < 0)//Perform v8.5 upgrade, add dfstarget { foreach (XmlNode n in doc.SelectNodes("/hapConfig/myfiles/quotaservers")) { ((XmlElement)n).SetAttribute("dfstarget", ""); } } if (version.CompareTo(Version.Parse("9.0.0215.1930")) < 0) //Perform v9 upgrade { XmlElement el = doc.SelectSingleNode("/hapConfig/SMTP") as XmlElement; if (el.Attributes["impersonationuser"] == null) { el.SetAttribute("impersonationuser", ""); el.SetAttribute("impersonationpassword", ""); el.SetAttribute("impersonationdomain", ""); } foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link")) { XmlElement en = n as XmlElement; en.SetAttribute("width", "1"); en.SetAttribute("height", "1"); if (en.Attributes["type"] != null && (en.GetAttribute("type") == "exchange.appointments" || en.GetAttribute("type").StartsWith("exchange.calendar") || en.GetAttribute("type") == "helpdesk" || en.GetAttribute("type") == "bookings")) { en.SetAttribute("width", "2"); } } } if (version.CompareTo(Version.Parse("9.0.0315.1900")) < 0) //Perform v9 upgrade { ((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).SetAttribute("usenestedlookups", "True"); ((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).SetAttribute("maxlogonattempts", "4"); } if (version.CompareTo(Version.Parse("9.0.0328.1900")) < 0) //Perform v9 upgrade { ((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).SetAttribute("maxrecursions", "10"); ((XmlElement)doc.SelectSingleNode("/hapConfig/HelpDesk")).SetAttribute("firstlineemails", doc.SelectSingleNode("/hapConfig/SMTP").Attributes["fromaddress"].Value); } if (version.CompareTo(Version.Parse("9.2.0526.0000")) < 0) //Perform v9.2 upgrade { foreach (XmlNode n in doc.SelectNodes("/hapConfig/bookingsystem/resources/resource")) { XmlElement e = n as XmlElement; e.SetAttribute("canshare", "False"); if (e.GetAttribute("enablecharging") == "True") { e.SetAttribute("chargingperiods", "1"); } } } if (version.CompareTo(Version.Parse("9.2.0528.0000")) < 0) //Perform v9.2 upgrade { foreach (XmlNode n in doc.SelectNodes("/hapConfig/bookingsystem/resources/resource")) { XmlElement e = n as XmlElement; e.SetAttribute("enablenotes", "false"); } } if (version.CompareTo(Version.Parse("9.2.0709.2000")) < 0) //Perform v9.2 upgrade { ((XmlElement)doc.SelectSingleNode("/hapConfig/bookingsystem")).SetAttribute("archive", "false"); } if (version.CompareTo(Version.Parse("9.4.0726.0")) < 0) //Perform v9.4 upgrade { ((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).SetAttribute("secureldap", "false"); } if (version.CompareTo(Version.Parse("9.6.0914.2000")) < 0) //Perform v9.6 upgrade { ((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).SetAttribute("allow1usecodes", "false"); XmlDocument doc2 = new XmlDocument(); doc2.Load(HttpContext.Current.Server.MapPath("~/App_Data/Bookings.xml")); foreach (XmlNode n in doc2.SelectNodes("/Bookings/Booking")) { XmlElement elem = n as XmlElement; if (elem.HasAttribute("ltcount")) { elem.SetAttribute("count", elem.GetAttribute("ltcount")); elem.RemoveAttribute("ltcount"); } } doc2.Save(HttpContext.Current.Server.MapPath("~/app_data/bookings.xml")); doc2 = new XmlDocument(); doc2.Load(HttpContext.Current.Server.MapPath("~/app_data/staticbookings.xml")); foreach (XmlNode n in doc.SelectNodes("/Bookings/Booking")) { XmlElement elem = n as XmlElement; if (elem.HasAttribute("ltcount")) { elem.SetAttribute("count", elem.GetAttribute("ltcount")); elem.RemoveAttribute("ltcount"); } } doc2.Save(HttpContext.Current.Server.MapPath("~/app_data/staticbookings.xml")); } if (version.CompareTo(Version.Parse("10.0.0223.2100")) < 0) //Perform v10 upgrade { XmlElement hap = doc.SelectSingleNode("/hapConfig") as XmlElement; hap.SetAttribute("maintenance", "false"); XmlElement hd = doc.SelectSingleNode("/hapConfig/HelpDesk") as XmlElement; hd.SetAttribute("provider", "xml"); hd.SetAttribute("priorities", "Low, Normal, High"); hd.SetAttribute("openstates", "New, With IT, Investigating, User Attention Needed, With 1st Line Support, With 2nd Line Support, With 3rd Line Support, Item Ordered, Waiting"); hd.SetAttribute("closedstates", "Completed, Fixed, No Action Needed, Resolved, Timed Out, User Fixed"); hd.SetAttribute("useropenstates", "New, Updated"); hd.SetAttribute("userclosedstates", "Fixed, No Action Needed, Self Fixed"); } if (version.CompareTo(Version.Parse("10.0.0319.2020")) < 0) // Perform v10 upgrade - allow multiple internal IP ranges { XmlElement hap = doc.SelectSingleNode("/hapConfig/AD") as XmlElement; XmlElement e = doc.CreateElement("InternalIPs"); if (hap.HasAttribute("internalip")) { XmlElement e1 = doc.CreateElement("InternalIP"); e1.SetAttribute("ip", hap.GetAttribute("internalip")); e.AppendChild(e1); } doc.SelectSingleNode("/hapConfig/AD").AppendChild(e); hap.RemoveAttribute("internalip"); foreach (XmlNode n in doc.SelectNodes("/hapConfig/Homepage/Links/Group/Link")) { XmlElement en = n as XmlElement; en.SetAttribute("access", "both"); } } if (version.CompareTo(Version.Parse("10.3.0917.1730")) < 0) // Perform v10.3 upgrade { ((XmlElement)doc.SelectSingleNode("/hapConfig/SMTP")).SetAttribute("tls", "False"); } if (version.CompareTo(Version.Parse("10.6.1801.0500")) < 0) // Perform v10.3 upgrade { if (!((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).HasAttribute("AuthMode")) { ((XmlElement)doc.SelectSingleNode("/hapConfig/AD")).SetAttribute("AuthMode", "Forms"); } } doc.SelectSingleNode("hapConfig").Attributes["version"].Value = Assembly.GetExecutingAssembly().GetName().Version.ToString(); doc.Save(ConfigPath); }
public static void ThrowUnknownAtributeValue(XmlAttribute attribute) { string text = string.Format("Error reading XML document \"{0}\": unknown value \"{1}\" of attribute \"{2}\" of node \"{3}\". Context: {4}", attribute.BaseURI, attribute.Value, attribute.Name, attribute.ParentNode.Name, attribute.OuterXml); throw new ArgumentNullException(text); }
public bool Save() { try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.AppendChild(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null)); XmlElement xmlRoot = xmlDocument.CreateElement("UnityGameFramework"); xmlDocument.AppendChild(xmlRoot); XmlElement xmlCollection = xmlDocument.CreateElement("ResourceCollection"); xmlRoot.AppendChild(xmlCollection); XmlElement xmlResources = xmlDocument.CreateElement("Resources"); xmlCollection.AppendChild(xmlResources); XmlElement xmlAssets = xmlDocument.CreateElement("Assets"); xmlCollection.AppendChild(xmlAssets); XmlElement xmlElement = null; XmlAttribute xmlAttribute = null; foreach (Resource resource in m_Resources.Values) { xmlElement = xmlDocument.CreateElement("Resource"); xmlAttribute = xmlDocument.CreateAttribute("Name"); xmlAttribute.Value = resource.Name; xmlElement.Attributes.SetNamedItem(xmlAttribute); if (resource.Variant != null) { xmlAttribute = xmlDocument.CreateAttribute("Variant"); xmlAttribute.Value = resource.Variant; xmlElement.Attributes.SetNamedItem(xmlAttribute); } if (resource.FileSystem != null) { xmlAttribute = xmlDocument.CreateAttribute("FileSystem"); xmlAttribute.Value = resource.FileSystem; xmlElement.Attributes.SetNamedItem(xmlAttribute); } xmlAttribute = xmlDocument.CreateAttribute("LoadType"); xmlAttribute.Value = ((byte)resource.LoadType).ToString(); xmlElement.Attributes.SetNamedItem(xmlAttribute); xmlAttribute = xmlDocument.CreateAttribute("Packed"); xmlAttribute.Value = resource.Packed.ToString(); xmlElement.Attributes.SetNamedItem(xmlAttribute); string[] resourceGroups = resource.GetResourceGroups(); if (resourceGroups.Length > 0) { xmlAttribute = xmlDocument.CreateAttribute("ResourceGroups"); xmlAttribute.Value = string.Join(",", resourceGroups); xmlElement.Attributes.SetNamedItem(xmlAttribute); } xmlResources.AppendChild(xmlElement); } foreach (Asset asset in m_Assets.Values) { xmlElement = xmlDocument.CreateElement("Asset"); xmlAttribute = xmlDocument.CreateAttribute("Guid"); xmlAttribute.Value = asset.Guid; xmlElement.Attributes.SetNamedItem(xmlAttribute); xmlAttribute = xmlDocument.CreateAttribute("ResourceName"); xmlAttribute.Value = asset.Resource.Name; xmlElement.Attributes.SetNamedItem(xmlAttribute); if (asset.Resource.Variant != null) { xmlAttribute = xmlDocument.CreateAttribute("ResourceVariant"); xmlAttribute.Value = asset.Resource.Variant; xmlElement.Attributes.SetNamedItem(xmlAttribute); } xmlAssets.AppendChild(xmlElement); } string configurationDirectoryName = Path.GetDirectoryName(m_ConfigurationPath); if (!Directory.Exists(configurationDirectoryName)) { Directory.CreateDirectory(configurationDirectoryName); } xmlDocument.Save(m_ConfigurationPath); AssetDatabase.Refresh(); return(true); } catch { if (File.Exists(m_ConfigurationPath)) { File.Delete(m_ConfigurationPath); } return(false); } }
private void CheckProperties(String msg, XmlAttribute attr, String value) { CheckProperties(msg, attr, attr.Prefix, attr.LocalName, attr.NamespaceURI, value); }
internal override void SetUnhandledAttributes(XmlAttribute[] moreAttributes) { this.moreAttributes = moreAttributes; }
public void ConstructorWithDouble() { var attribute = new XmlAttribute("name", 3.14); Assert.AreEqual("name", attribute.Name); Assert.AreEqual("3.14", attribute.Value); }
/// <summary> /// Writes the specified configuration into the specified XML element /// </summary> /// <param name="configuration">Configuration to write.</param> /// <param name="parent">Parent element in the XML tree.</param> /// <param name="flags">Flags controlling the saving behavior.</param> private void SaveInternal(CascadedConfiguration configuration, XmlElement parent, CascadedConfigurationSaveFlags flags) { // create 'Configuration' element XmlElement configurationElement = parent.SelectSingleNode(string.Format("Configuration[@name='{0}']", configuration.Name)) as XmlElement; if (configurationElement == null) { configurationElement = parent.OwnerDocument.CreateElement("Configuration"); XmlAttribute configurationNameAttribute = parent.OwnerDocument.CreateAttribute("name"); configurationNameAttribute.InnerText = configuration.Name; configurationElement.Attributes.Append(configurationNameAttribute); parent.AppendChild(configurationElement); } foreach (ICascadedConfigurationItem item in configuration.Items) { if (item.HasValue || flags.HasFlag(CascadedConfigurationSaveFlags.SaveInheritedSettings)) { XmlElement itemElement = SetItem(configurationElement, configuration, item.Name, item.Type, item.Value); // remove all comment nodes before the node for (int i = 0; i < configurationElement.ChildNodes.Count; i++) { XmlNode node = configurationElement.ChildNodes[i]; if (node == itemElement) { for (int j = i; j > 0; j--) { node = configurationElement.ChildNodes[j - 1]; if (node.NodeType != XmlNodeType.Comment) { break; } configurationElement.RemoveChild(node); } break; } } // add comment nodes if (item.Comment != null) { string[] commentLines = item.Comment.Split('\n'); foreach (string commentLine in commentLines) { string line = commentLine.Trim(); if (line.Length > 0) { XmlComment commentNode = configurationElement.OwnerDocument.CreateComment(line); configurationElement.InsertBefore(commentNode, itemElement); } } } } else { RemoveItem(configurationElement, item.Name); } } // save child configurations foreach (CascadedConfiguration child in configuration.Children) { SaveInternal(child, configurationElement, flags); } }
/// <summary> /// Appends the attribute. /// </summary> /// <param name="node">The node.</param> /// <param name="nodeAttribute">The node attribute.</param> private static void AppendAttribute(XmlNode node, XmlAttribute nodeAttribute) { var attribute = _xmlDoc.CreateAttribute(nodeAttribute.Name); attribute.Value = nodeAttribute.Value; if (node.Attributes != null) node.Attributes.Append(attribute); }
internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o) { this.attr = attr; this.o = o; this.lineNumber = lineNumber; this.linePosition = linePosition; }
public void ConstructorWithObject() { var attribute = new XmlAttribute("name", DayOfWeek.Friday); Assert.AreEqual("name", attribute.Name); Assert.AreEqual("Friday", attribute.Value); }
public void ConstructorWithChar() { var attribute = new XmlAttribute("name", 'a'); Assert.AreEqual("name", attribute.Name); Assert.AreEqual("a", attribute.Value); }
/// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlElement element, string attributeName) { XmlAttribute attr = element.GetAttributeNode(attributeName); return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; }
/// <summary> /// Reads an exported XGE task list /// </summary> /// <param name="TaskListFile">File to read from</param> /// <param name="FileToEnvironment">Mapping from source file to compile environment</param> public static void ReadTaskList(FileReference TaskListFile, DirectoryReference BaseDir, out Dictionary <FileReference, CompileEnvironment> FileToEnvironment) { XmlDocument Document = new XmlDocument(); Document.Load(TaskListFile.FullName); // Read the standard include paths from the INCLUDE environment variable in the script List <DirectoryReference> StandardIncludePaths = new List <DirectoryReference>(); foreach (XmlNode Node in Document.SelectNodes("BuildSet/Environments/Environment/Variables/Variable")) { XmlAttribute NameAttr = Node.Attributes["Name"]; if (NameAttr != null && String.Compare(NameAttr.InnerText, "INCLUDE") == 0) { foreach (string IncludePath in Node.Attributes["Value"].InnerText.Split(';')) { StandardIncludePaths.Add(new DirectoryReference(IncludePath)); } } } // Read all the individual compiles Dictionary <FileReference, CompileEnvironment> NewFileToEnvironment = new Dictionary <FileReference, CompileEnvironment>(); foreach (XmlNode Node in Document.SelectNodes("BuildSet/Environments/Environment/Tools/Tool")) { XmlAttribute ToolPathAttr = Node.Attributes["Path"]; if (ToolPathAttr != null) { // Get the full path to the tool FileReference ToolLocation = new FileReference(ToolPathAttr.InnerText); // Get the compiler type CompilerType CompilerType; if (GetCompilerType(ToolLocation, out CompilerType)) { string Name = Node.Attributes["Name"].InnerText; string Params = Node.Attributes["Params"].InnerText; // Construct the compile environment CompileEnvironment Environment = new CompileEnvironment(ToolLocation, CompilerType); // Parse a list of tokens List <string> Tokens = new List <string>(); ParseArgumentTokens(CompilerType, Params, Tokens); // Parse it into a list of options, removing any that don't apply List <FileReference> SourceFiles = new List <FileReference>(); List <FileReference> OutputFiles = new List <FileReference>(); for (int Idx = 0; Idx < Tokens.Count; Idx++) { if (Tokens[Idx] == "/Fo" || Tokens[Idx] == "/Fp" || Tokens[Idx] == "-o") { OutputFiles.Add(new FileReference(Tokens[++Idx])); } else if (Tokens[Idx].StartsWith("/Fo") || Tokens[Idx].StartsWith("/Fp")) { OutputFiles.Add(new FileReference(Tokens[Idx].Substring(3))); } else if (Tokens[Idx] == "/D" || Tokens[Idx] == "-D") { Environment.Definitions.Add(Tokens[++Idx]); } else if (Tokens[Idx].StartsWith("/D")) { Environment.Definitions.Add(Tokens[Idx].Substring(2)); } else if (Tokens[Idx] == "/I" || Tokens[Idx] == "-I") { Environment.IncludePaths.Add(new DirectoryReference(DirectoryReference.Combine(BaseDir, Tokens[++Idx].Replace("//", "/")).FullName.ToLowerInvariant())); } else if (Tokens[Idx].StartsWith("-I")) { Environment.IncludePaths.Add(new DirectoryReference(DirectoryReference.Combine(BaseDir, Tokens[Idx].Substring(2).Replace("//", "/")).FullName.ToLowerInvariant())); } else if (Tokens[Idx].StartsWith("/FI")) { Environment.ForceIncludeFiles.Add(new FileReference(Tokens[Idx].Substring(3))); } else if (Tokens[Idx] == "-include") { Environment.ForceIncludeFiles.Add(new FileReference(Tokens[++Idx])); } else if (Tokens[Idx] == "-Xclang" || Tokens[Idx] == "-target" || Tokens[Idx] == "--target" || Tokens[Idx] == "-x" || Tokens[Idx] == "-o") { Environment.Options.Add(new CompileOption(Tokens[Idx], Tokens[++Idx])); } else if (Tokens[Idx].StartsWith("/") || Tokens[Idx].StartsWith("-")) { Environment.Options.Add(new CompileOption(Tokens[Idx], null)); } else { SourceFiles.Add(FileReference.Combine(BaseDir, Tokens[Idx])); } } // Make sure we're not compiling a precompiled header if (!OutputFiles.Any(x => x.HasExtension(".gch")) && !Environment.Options.Any(x => x.Name.StartsWith("/Yc"))) { // Add all the standard include paths Environment.IncludePaths.AddRange(StandardIncludePaths); // Add to the output map if there are any source files. Use the extension to distinguish between a source file and linker invocation on Clang. foreach (FileReference SourceFile in SourceFiles) { if (!SourceFile.HasExtension(".a")) { NewFileToEnvironment.Add(SourceFile, Environment); } } } } } } FileToEnvironment = NewFileToEnvironment; }
internal void AddUnrendered(XmlAttribute attr) { _unrendered.Add(Utils.GetNamespacePrefix(attr), attr); }
protected void ParseWsdlArrayType(XmlAttribute attr);
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { if (xmlNodeDefinition == null) { // maybe the existing properties can be edited? ArrayList properties = new ArrayList(); foreach (XmlAttribute xmlAttribute in xmlNode.Attributes) { // We could add an UITypeEditor if desired ArrayList attrs = new ArrayList(); attrs.Add(new EditorAttribute(typeof(UITypeEditor), typeof(UITypeEditor))); attrs.Add(new CategoryAttribute("WXS Attribute")); attrs.Add(new TypeConverterAttribute(typeof(StringConverter))); // Make Attribute array Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute)); // Create and add PropertyDescriptor XmlAttributePropertyDescriptor pd = new XmlAttributePropertyDescriptor(wixFiles, xmlAttribute, null, xmlAttribute.Name, attrArray); properties.Add(pd); } PropertyDescriptor[] propertiesArray = properties.ToArray(typeof(PropertyDescriptor)) as PropertyDescriptor[]; return(new PropertyDescriptorCollection(propertiesArray)); } ArrayList props = new ArrayList(); // Show all existing + required elements XmlNodeList xmlAttributeDefinitions = xmlNodeDefinition.SelectNodes("xs:attribute", wixFiles.XsdNsmgr); foreach (XmlNode xmlAttributeDefinition in xmlAttributeDefinitions) { XmlAttribute xmlAttribute = xmlNode.Attributes[xmlAttributeDefinition.Attributes["name"].Value]; if (xmlAttribute == null) { if (xmlAttributeDefinition.Attributes["use"] == null || xmlAttributeDefinition.Attributes["use"].Value != "required") { continue; } // If there is no attibute present, create one. if (xmlAttribute == null) { // Do not call UndoManager.BeginNewCommandRange here, because this can happen after // an undo/redo action when viewing some node. That would mess up the undo mechanism. // So the adding of mandatory attributes will be added to the last undo command sequence. xmlAttribute = xmlNode.OwnerDocument.CreateAttribute(xmlAttributeDefinition.Attributes["name"].Value); xmlNode.Attributes.Append(xmlAttribute); } } ArrayList attrs = new ArrayList(); // Add default attributes Category, TypeConverter and Description attrs.Add(new CategoryAttribute("WXS Attribute")); attrs.Add(new TypeConverterAttribute(GetAttributeTypeConverter(xmlAttributeDefinition))); // Get some documentation XmlNode deprecated = xmlAttributeDefinition.SelectSingleNode("xs:annotation/xs:appinfo/xse:deprecated", wixFiles.XsdNsmgr); XmlNode documentation = xmlAttributeDefinition.SelectSingleNode("xs:annotation/xs:documentation", wixFiles.XsdNsmgr); if (deprecated != null || documentation != null) { string docuString = ""; if (deprecated != null) { docuString = "** DEPRECATED **\r\n"; } if (documentation != null) { docuString = documentation.InnerText; docuString = docuString.Replace("\t", " "); docuString = docuString.Replace("\r\n", " "); } string tmpDocuString = docuString; do { docuString = tmpDocuString; tmpDocuString = docuString.Replace(" ", " "); } while (docuString != tmpDocuString); docuString = tmpDocuString; docuString = docuString.Trim(' '); attrs.Add(new DescriptionAttribute(docuString)); } bool needsBrowse = false; if (xmlAttributeDefinition.Attributes["name"] != null) { string attName = xmlNodeElement.Attributes["name"].Value; if (xmlAttributeDefinition.Attributes["name"].Value == "SourceFile") { needsBrowse = true; } else if (xmlAttributeDefinition.Attributes["name"].Value == "Source") { needsBrowse = true; } else if (xmlAttributeDefinition.Attributes["name"].Value == "FileSource") { needsBrowse = true; } else if (xmlAttributeDefinition.Attributes["name"].Value == "Layout") { needsBrowse = true; } else if (xmlAttributeDefinition.Attributes["name"].Value == "src") { needsBrowse = true; } } if (needsBrowse) { // We could add an UITypeEditor if desired attrs.Add(new EditorAttribute(typeof(FilteredFileNameEditor), typeof(System.Drawing.Design.UITypeEditor))); // Make Attribute array Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute)); // BinaryElementPropertyDescriptor also uses the src attribute, and a possibility to use relative paths. FileXmlAttributePropertyDescriptor pd = new FileXmlAttributePropertyDescriptor(xmlNode, wixFiles, xmlAttributeDefinition, xmlAttributeDefinition.Attributes["name"].Value, attrArray); props.Add(pd); } else { // We could add an UITypeEditor if desired // attrs.Add(new EditorAttribute(?property.EditorTypeName?, typeof(UITypeEditor))); attrs.Add(new EditorAttribute(GetAttributeEditor(xmlAttributeDefinition), typeof(UITypeEditor))); // Make Attribute array Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute)); // Create and add PropertyDescriptor XmlAttributePropertyDescriptor pd = new XmlAttributePropertyDescriptor(wixFiles, xmlAttribute, xmlAttributeDefinition, xmlAttributeDefinition.Attributes["name"].Value, attrArray); props.Add(pd); } } // Add InnerText if required or present. if ( (XmlNodeDefinition.Name == "xs:extension" && ((xmlNode.InnerText != null && xmlNode.InnerText.Length > 0) || showInnerTextIfEmpty == true)) || (XmlNodeDefinition.Name == "xs:element" && showInnerTextIfEmpty == true)) { ArrayList attrs = new ArrayList(); // Add default attributes Category, TypeConverter and Description attrs.Add(new CategoryAttribute("WXS Attribute")); attrs.Add(new TypeConverterAttribute(typeof(StringConverter))); attrs.Add(new EditorAttribute(typeof(MultiLineUITypeEditor), typeof(UITypeEditor))); attrs.Add(new DescriptionAttribute("InnerText of the element.")); // Make Attribute array Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute)); // Create and add PropertyDescriptor InnerTextPropertyDescriptor pd = new InnerTextPropertyDescriptor(wixFiles, xmlNode, attrArray); props.Add(pd); } if (editSubNodes) { XmlNodeList subNodes = xmlNode.SelectNodes("*", WixFiles.WxsNsmgr); if (subNodes.Count >= 1) { ArrayList attrs = new ArrayList(); if (subNodes.Count == 1) { attrs.Add(new EditorAttribute(typeof(SearchElementTypeEditor), typeof(UITypeEditor))); attrs.Add(new DescriptionAttribute("Sub Elements of the element.")); } // Make Attribute array Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute)); // Create and add PropertyDescriptor PropertySearchElementPropertyDescriptor pd = new PropertySearchElementPropertyDescriptor(wixFiles, xmlNode, "SubElements", attrArray); props.Add(pd); } } PropertyDescriptor[] propArray = props.ToArray(typeof(PropertyDescriptor)) as PropertyDescriptor[]; return(new PropertyDescriptorCollection(propArray)); }
public void ConstructorWithFloat() { var attribute = new XmlAttribute("name", 2.1f); Assert.AreEqual("name", attribute.Name); Assert.AreEqual("2.1", attribute.Value); }
/*XML Information * ================*/ public string ToXmlString() { XmlDocument playerData = new XmlDocument(); XmlNode player = playerData.CreateElement("Player"); playerData.AppendChild(player); // Create the "Stats" child node to hold the other player statistics nodes XmlNode stats = playerData.CreateElement("Stats"); player.AppendChild(stats); // Create the child nodes for the "Stats" node XmlNode currentHitPoints = playerData.CreateElement("CurrentHitPoints"); currentHitPoints.AppendChild(playerData.CreateTextNode(this.CurrentHitPoints.ToString())); stats.AppendChild(currentHitPoints); XmlNode maximumHitPoints = playerData.CreateElement("MaximumHitPoints"); maximumHitPoints.AppendChild(playerData.CreateTextNode(this.MaximumHitPoints.ToString())); stats.AppendChild(maximumHitPoints); XmlNode gold = playerData.CreateElement("Gold"); gold.AppendChild(playerData.CreateTextNode(this.Gold.ToString())); stats.AppendChild(gold); XmlNode experiencePoints = playerData.CreateElement("ExperiencePoints"); experiencePoints.AppendChild(playerData.CreateTextNode(this.ExperiencePoints.ToString())); stats.AppendChild(experiencePoints); XmlNode currentLocation = playerData.CreateElement("CurrentLocation"); currentLocation.AppendChild(playerData.CreateTextNode(this.CurrentLocation.ID.ToString())); stats.AppendChild(currentLocation); if (CurrentWeapon != null) { XmlNode currentWeapon = playerData.CreateElement("CurrentWeapon"); currentWeapon.AppendChild(playerData.CreateTextNode(this.CurrentWeapon.ID.ToString())); stats.AppendChild(currentWeapon); } // Create the "InventoryItems" child node to hold each InventoryItem node XmlNode inventoryItems = playerData.CreateElement("InventoryItems"); player.AppendChild(inventoryItems); // Create an "InventoryItem" node for each item in the player's inventory foreach (InventoryItem item in this.Inventory) { XmlNode inventoryItem = playerData.CreateElement("InventoryItem"); XmlAttribute idAttribute = playerData.CreateAttribute("ID"); idAttribute.Value = item.Details.ID.ToString(); inventoryItem.Attributes.Append(idAttribute); XmlAttribute quantityAttribute = playerData.CreateAttribute("Quantity"); quantityAttribute.Value = item.Quantity.ToString(); inventoryItem.Attributes.Append(quantityAttribute); inventoryItems.AppendChild(inventoryItem); } // Create the "PlayerQuests" child node to hold each PlayerQuest node XmlNode playerQuests = playerData.CreateElement("PlayerQuests"); player.AppendChild(playerQuests); // Create a "PlayerQuest" node for each quest the player has acquired foreach (PlayerQuest quest in this.Quests) { XmlNode playerQuest = playerData.CreateElement("PlayerQuest"); XmlAttribute idAttribute = playerData.CreateAttribute("ID"); idAttribute.Value = quest.Details.ID.ToString(); playerQuest.Attributes.Append(idAttribute); XmlAttribute isCompletedAttribute = playerData.CreateAttribute("IsCompleted"); isCompletedAttribute.Value = quest.IsCompleted.ToString(); playerQuest.Attributes.Append(isCompletedAttribute); playerQuests.AppendChild(playerQuest); } return(playerData.InnerXml); // The XML document, as a string, so we can save the data to disk }
private Vector3 parse_vec3(XmlAttribute vec3_attrib) { string value = vec3_attrib.Value; string[] values = value.Split(','); float x = float.Parse(values[2]); float y = float.Parse(values[1]); float z = float.Parse(values[0]); return new Vector3(x, y, z); }
public override void ImportDocumentation(DocsNodeInfo info) { XmlNode elem = GetDocs(info.Member ?? info.Type); if (elem == null) { return; } XmlElement e = info.Node; if (elem.SelectSingleNode("summary") != null && DocUtils.NeedsOverwrite(e["summary"])) { MDocUpdater.ClearElement(e, "summary"); } if (elem.SelectSingleNode("remarks") != null && DocUtils.NeedsOverwrite(e["remarks"])) { MDocUpdater.ClearElement(e, "remarks"); } if (elem.SelectSingleNode("value") != null || elem.SelectSingleNode("returns") != null) { if (DocUtils.NeedsOverwrite(e["value"])) { MDocUpdater.ClearElement(e, "value"); } if (DocUtils.NeedsOverwrite(e["returns"])) { MDocUpdater.ClearElement(e, "returns"); } } foreach (XmlNode child in elem.ChildNodes) { switch (child.Name) { case "param": case "typeparam": { XmlAttribute name = child.Attributes["name"]; if (name == null) { break; } XmlElement p2 = (XmlElement)e.SelectSingleNode(child.Name + "[@name='" + name.Value + "']"); if (DocUtils.NeedsOverwrite(p2)) { p2.RemoveAttribute("overwrite"); p2.InnerXml = child.InnerXml; } break; } // Occasionally XML documentation will use <returns/> on // properties, so let's try to normalize things. case "value": case "returns": { XmlElement v = e.OwnerDocument.CreateElement(info.ReturnIsReturn ? "returns" : "value"); XmlElement p2 = (XmlElement)e.SelectSingleNode(child.Name); if (p2 == null) { v.InnerXml = child.InnerXml; e.AppendChild(v); } break; } case "altmember": case "exception": case "permission": { XmlAttribute cref = child.Attributes["cref"] ?? child.Attributes["name"]; if (cref == null) { break; } XmlElement a = (XmlElement)e.SelectSingleNode(child.Name + "[@cref='" + cref.Value + "']"); if (a == null) { a = e.OwnerDocument.CreateElement(child.Name); a.SetAttribute("cref", cref.Value); e.AppendChild(a); } if (DocUtils.NeedsOverwrite(a)) { a.InnerXml = child.InnerXml; } break; } case "seealso": { XmlAttribute cref = child.Attributes["cref"]; if (cref == null) { break; } XmlElement a = (XmlElement)e.SelectSingleNode("altmember[@cref='" + cref.Value + "']"); if (a == null) { a = e.OwnerDocument.CreateElement("altmember"); a.SetAttribute("cref", cref.Value); e.AppendChild(a); } break; } default: { var targetNodes = e.ChildNodes.Cast <XmlNode> () .Where(n => n.Name == child.Name) .Select(n => new { Xml = n.OuterXml, Overwrite = n.Attributes != null ? n.Attributes["overwrite"] : null }); string sourceXml = child.OuterXml; if (!targetNodes.Any(n => sourceXml.Equals(n.Xml) || n.Overwrite?.Value == "false")) { MDocUpdater.CopyNode(child, e); } break; } } } }
/// <summary> /// Method to add an attribute rule to this element. /// </summary> /// <param name="_attribute">The attribute rule to add.</param> public void addAttribute(XmlAttribute _attribute) { this.Attributes.Add(_attribute); }
internal virtual void SetUnhandledAttributes(XmlAttribute[] moreAttributes) {}
/// <summary> /// Method to remove an attribute to this element. /// </summary> /// <param name="_attribute">The attribute rule to remove.</param> public void removeAttribute(XmlAttribute _attribute) { while(this.Attributes.Remove(_attribute)); }
public override string ToText(Subtitle subtitle, string title) { string guid = new Guid().ToString(); string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<OpenDVT UUID=\"{" + guid + "\" ShortID=\"" + title + "\" Type=\"Deposition\" Version=\"1.3\">" + Environment.NewLine + "<Information>" + Environment.NewLine + " <Origination>" + Environment.NewLine + " <ID>" + guid + "</ID> " + Environment.NewLine + " <AppName>Subtitle Edit</AppName> " + Environment.NewLine + " <AppVersion>2.9</AppVersion> " + Environment.NewLine + " <VendorName>Nikse.dk</VendorName> " + Environment.NewLine + " <VendorPhone></VendorPhone> " + Environment.NewLine + " <VendorURL>www.nikse.dk.com</VendorURL> " + Environment.NewLine + " </Origination>" + Environment.NewLine + " <Case>" + Environment.NewLine + " <MatterNumber /> " + Environment.NewLine + " </Case>" + Environment.NewLine + " <Deponent>" + Environment.NewLine + " <FirstName></FirstName> " + Environment.NewLine + " <LastName></LastName> " + Environment.NewLine + " </Deponent>" + Environment.NewLine + " <ReportingFirm>" + Environment.NewLine + " <Name /> " + Environment.NewLine + " </ReportingFirm>" + Environment.NewLine + " <FirstPageNo>1</FirstPageNo> " + Environment.NewLine + " <LastPageNo>3</LastPageNo> " + Environment.NewLine + " <MaxLinesPerPage>25</MaxLinesPerPage> " + Environment.NewLine + " <Volume>1</Volume> " + Environment.NewLine + " <TakenOn>06/02/2010</TakenOn> " + Environment.NewLine + " <TranscriptVerify></TranscriptVerify> " + Environment.NewLine + " <PrintVerify></PrintVerify> " + Environment.NewLine + " </Information>" + Environment.NewLine + "<Lines Count=\"" + subtitle.Paragraphs.Count + "\">" + Environment.NewLine + "</Lines>" + Environment.NewLine + "<Streams Count=\"0\">" + Environment.NewLine + "<Stream ID=\"0\">" + Environment.NewLine + //"<URI>C:\Users\Eric\Desktop\Player Folder\Bing\Bing.mpg</URI> //"<FileSize>52158464</FileSize> //"<FileDate>06/02/2009 10:44:37</FileDate> //"<DurationMs>166144</DurationMs> //"<VolumeLabel>OS</VolumeLabel> " </Stream>" + Environment.NewLine + "</Streams>" + Environment.NewLine + "</OpenDVT>"; XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlStructure); XmlNode lines = xml.DocumentElement.SelectSingleNode("Lines"); int no = 0; foreach (Paragraph p in subtitle.Paragraphs) { XmlNode line = xml.CreateElement("Line"); XmlAttribute id = xml.CreateAttribute("ID"); id.InnerText = no.ToString(); line.Attributes.Append(id); XmlNode stream = xml.CreateElement("Stream"); stream.InnerText = "0"; line.AppendChild(stream); XmlNode timeMS = xml.CreateElement("TimeMs"); timeMS.InnerText = p.StartTime.TotalMilliseconds.ToString(); line.AppendChild(timeMS); XmlNode pageNo = xml.CreateElement("PageNo"); pageNo.InnerText = "1"; line.AppendChild(pageNo); XmlNode lineNo = xml.CreateElement("LineNo"); lineNo.InnerText = "1"; line.AppendChild(lineNo); XmlNode qa = xml.CreateElement("QA"); qa.InnerText = "-"; line.AppendChild(qa); XmlNode text = xml.CreateElement("Text"); text.InnerText = p.Text; line.AppendChild(text); lines.AppendChild(line); no++; } MemoryStream ms = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8); writer.Formatting = Formatting.Indented; xml.Save(writer); return(Encoding.UTF8.GetString(ms.ToArray()).Trim()); }
public XmlAttribute Append(XmlAttribute node) { }
public override string ToText(Subtitle subtitle, string title) { string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<tt xmlns=\"http://www.w3.org/ns/ttml\" xmlns:ttp=\"http://www.w3.org/ns/ttml#parameter\" ttp:timeBase=\"media\" xmlns:tts=\"http://www.w3.org/ns/ttml#style\" xml:lang=\"en\" xmlns:ttm=\"http://www.w3.org/ns/ttml#metadata\">" + Environment.NewLine + " <head>" + Environment.NewLine + " <metadata>" + Environment.NewLine + " <ttm:title></ttm:title>" + Environment.NewLine + " </metadata>" + Environment.NewLine + " <styling>" + Environment.NewLine + " <style id=\"s0\" tts:backgroundColor=\"black\" tts:fontStyle=\"normal\" tts:fontSize=\"16\" tts:fontFamily=\"sansSerif\" tts:color=\"white\" />" + Environment.NewLine + " </styling>" + Environment.NewLine + " </head>" + Environment.NewLine + " <body style=\"s0\">" + Environment.NewLine + " <div />" + Environment.NewLine + " </body>" + Environment.NewLine + "</tt>"; XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlStructure); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable); nsmgr.AddNamespace("ttml", "http://www.w3.org/ns/ttml"); nsmgr.AddNamespace("ttp", "http://www.w3.org/ns/10/ttml#parameter"); nsmgr.AddNamespace("tts", "http://www.w3.org/ns/10/ttml#style"); nsmgr.AddNamespace("ttm", "http://www.w3.org/ns/10/ttml#metadata"); XmlNode titleNode = xml.DocumentElement.SelectSingleNode("//ttml:head", nsmgr).FirstChild.FirstChild; titleNode.InnerText = title; XmlNode div = xml.DocumentElement.SelectSingleNode("//ttml:body", nsmgr).FirstChild; int no = 0; foreach (Paragraph p in subtitle.Paragraphs) { XmlNode paragraph = xml.CreateElement("p", "http://www.w3.org/ns/ttml"); string text = Utilities.RemoveHtmlTags(p.Text); bool first = true; foreach (string line in text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { if (!first) { XmlNode br = xml.CreateElement("br", "http://www.w3.org/ns/ttml"); paragraph.AppendChild(br); } XmlNode textNode = xml.CreateTextNode(line); paragraph.AppendChild(textNode); first = false; } XmlAttribute start = xml.CreateAttribute("begin"); start.InnerText = ConvertToTimeString(p.StartTime); paragraph.Attributes.Append(start); XmlAttribute id = xml.CreateAttribute("id"); id.InnerText = "p" + no.ToString(); paragraph.Attributes.Append(id); XmlAttribute end = xml.CreateAttribute("end"); end.InnerText = ConvertToTimeString(p.EndTime); paragraph.Attributes.Append(end); div.AppendChild(paragraph); no++; } MemoryStream ms = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8); writer.Formatting = Formatting.Indented; xml.Save(writer); return(Encoding.UTF8.GetString(ms.ToArray()).Trim()); }
public void CopyTo(XmlAttribute[] array, int index) { }
public void AppendTimeXMLNode(XmlDocument XmlDocument) { XmlNode element = XmlDocument.CreateElement("TimeSettings"); XmlDocument.DocumentElement.AppendChild(element); // указываем родителя XmlAttribute attribute = XmlDocument.CreateAttribute("TimeFormat"); // создаём атрибут attribute.Value = timeFormat.ToString(); element.Attributes.Append(attribute); // добавляем атрибут if (timeFormat == TimeFormats.ADSPFormat) { attribute = XmlDocument.CreateAttribute("ReadAddr"); // создаём атрибут attribute.Value = ReadAddr.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("SetAddr"); // создаём атрибут attribute.Value = SetAddr.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("AddrSetTime"); // создаём атрибут attribute.Value = AddrSetTime.ToString(); element.Attributes.Append(attribute); // добавляем атрибут } if (timeFormat == TimeFormats.STMFormat) { attribute = XmlDocument.CreateAttribute("STMProcAddr1"); // создаём атрибут attribute.Value = STMProcAddr1.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr2"); // создаём атрибут attribute.Value = STMProcAddr2.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr3"); // создаём атрибут attribute.Value = STMProcAddr3.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr4"); // создаём атрибут attribute.Value = STMProcAddr4.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr1_1"); // создаём атрибут attribute.Value = STMProcAddr1_1.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr2_1"); // создаём атрибут attribute.Value = STMProcAddr2_1.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr3_1"); // создаём атрибут attribute.Value = STMProcAddr3_1.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("STMProcAddr4_1"); // создаём атрибут attribute.Value = STMProcAddr4_1.ToString(); element.Attributes.Append(attribute); // добавляем атрибут } if (timeFormat == TimeFormats.RTCFormat) { attribute = XmlDocument.CreateAttribute("ReadAddr"); // создаём атрибут attribute.Value = ReadAddr.ToString(); element.Attributes.Append(attribute); // добавляем атрибут attribute = XmlDocument.CreateAttribute("SetAddr"); // создаём атрибут attribute.Value = SetAddr.ToString(); element.Attributes.Append(attribute); // добавляем атрибут } }
public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode) { }
/// <summary> /// Gets the value of the attribute, or null if the attribute does not exist. /// </summary> public static string GetAttributeOrNull(this XmlElement element, string attributeName) { XmlAttribute attr = element.GetAttributeNode(attributeName); return attr != null ? attr.Value : null; }
public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode) { }
/// <summary> /// Processes an attribute for the Compiler. /// </summary> /// <param name="sourceLineNumbers">Source line number for the parent element.</param> /// <param name="parentElement">Parent element of attribute.</param> /// <param name="attribute">Attribute to process.</param> public override void ParseAttribute(SourceLineNumberCollection sourceLineNumbers, XmlElement parentElement, XmlAttribute attribute) { this.Core.UnexpectedAttribute(sourceLineNumbers, attribute); }
public XmlAttribute Prepend(XmlAttribute node) { }
internal VcProjectConfiguration(XmlElement elem, VcProject parentProject, DirectoryInfo outputDir) : base(elem, parentProject, outputDir) { // determine relative output directory (outdir) XmlAttribute outputDirAttribute = elem.Attributes["OutputDirectory"]; if (outputDirAttribute != null) { _rawRelativeOutputDir = outputDirAttribute.Value; } // get intermediate directory and expand macros XmlAttribute intermidiateDirAttribute = elem.Attributes["IntermediateDirectory"]; if (intermidiateDirAttribute != null) { _rawIntermediateDir = intermidiateDirAttribute.Value; } // get referencespath directory and expand macros XmlAttribute referencesPathAttribute = elem.Attributes["ReferencesPath"]; if (referencesPathAttribute != null) { _rawReferencesPath = StringUtils.ConvertEmptyToNull(referencesPathAttribute.Value); } string managedExtentions = GetXmlAttributeValue(elem, "ManagedExtensions"); if (managedExtentions != null) { switch (managedExtentions.ToLower()) { case "false": case "0": _managedExtensions = false; break; case "true": case "1": _managedExtensions = true; break; default: throw new BuildException(String.Format("ManagedExtensions '{0}' is not supported yet.", managedExtentions)); } } // get configuration type string type = GetXmlAttributeValue(elem, "ConfigurationType"); if (type != null) { _type = (ConfigurationType)Enum.ToObject(typeof(ConfigurationType), int.Parse(type, CultureInfo.InvariantCulture)); } string wholeProgramOptimization = GetXmlAttributeValue(elem, "WholeProgramOptimization"); if (wholeProgramOptimization != null) { _wholeProgramOptimization = string.Compare(wholeProgramOptimization.Trim(), "true", true, CultureInfo.InvariantCulture) == 0; } string characterSet = GetXmlAttributeValue(elem, "CharacterSet"); if (characterSet != null) { _characterSet = (CharacterSet)Enum.ToObject(typeof(CharacterSet), int.Parse(characterSet, CultureInfo.InvariantCulture)); } // get MFC settings string useOfMFC = GetXmlAttributeValue(elem, "UseOfMFC"); if (useOfMFC != null) { _useOfMFC = (UseOfMFC)Enum.ToObject(typeof(UseOfMFC), int.Parse(useOfMFC, CultureInfo.InvariantCulture)); } // get ATL settings string useOfATL = GetXmlAttributeValue(elem, "UseOfATL"); if (useOfATL != null) { _useOfATL = (UseOfATL)Enum.ToObject(typeof(UseOfATL), int.Parse(useOfATL, CultureInfo.InvariantCulture)); } _linkerConfiguration = new LinkerConfig(this); }
public XmlAttribute Remove(XmlAttribute node) { }
public object Create(object parent, object configContext, XmlNode section) { MonoRailConfiguration config = new MonoRailConfiguration(); config.ConfigSection = section; XmlAttribute useWindsorAtt = section.Attributes["useWindsorIntegration"]; if (useWindsorAtt != null && "true".Equals(useWindsorAtt.Value)) { ConfigureWindsorIntegration(config); } XmlAttribute smtpHostAtt = section.Attributes["smtpHost"]; XmlAttribute smtpUserAtt = section.Attributes["smtpUsername"]; XmlAttribute smtpPwdAtt = section.Attributes["smtpPassword"]; if (smtpHostAtt != null && smtpHostAtt.Value != String.Empty) { config.SmtpConfig.Host = smtpHostAtt.Value; } if (smtpUserAtt != null && smtpUserAtt.Value != String.Empty) { config.SmtpConfig.Username = smtpUserAtt.Value; } if (smtpPwdAtt != null && smtpPwdAtt.Value != String.Empty) { config.SmtpConfig.Password = smtpPwdAtt.Value; } foreach (XmlNode node in section.ChildNodes) { if (node.NodeType != XmlNodeType.Element) { continue; } if (String.Compare(Controllers_Node_Name, node.Name, true) == 0) { ProcessControllersNode(node, config); } else if (String.Compare(Components_Node_Name, node.Name, true) == 0) { ProcessComponentsNode(node, config); } else if (String.Compare(Views_Node_Name, node.Name, true) == 0) { ProcessViewNode(node, config); } else if (String.Compare(Custom_Controller_Factory_Node_Name, node.Name, true) == 0) { ProcessControllerFactoryNode(node, config); } else if (String.Compare(Custom_Component_Factory_Node_Name, node.Name, true) == 0) { ProcessComponentFactoryNode(node, config); } else if (String.Compare(Custom_Filter_Factory_Node_Name, node.Name, true) == 0) { ProcessFilterFactoryNode(node, config); } else if (String.Compare(Routing_Node_Name, node.Name, true) == 0) { ProcessRoutingNode(node, config); } else if (String.Compare(Extensions_Node_Name, node.Name, true) == 0) { ProcessExtensionsNode(node, config); } } Validate(config); return(config); }
///<summary> ///</summary> ///<param name="Parentelement"></param> ///<param name="Attribute"></param> public void RemoveAttributes(XmlNode Parentelement, XmlAttribute Attribute) { Parentelement.Attributes.Remove(Attribute); }
protected override void HandleRequest() { byte[] status = null; string span = ""; switch (Query["timespan"]) { case "week": span = "(time >= DATE_SUB(NOW(), INTERVAL 1 WEEK))"; break; case "month": span = "(time >= DATE_SUB(NOW(), INTERVAL 1 MONTH))"; break; case "all": span = "TRUE"; break; default: status = Encoding.UTF8.GetBytes("<Error>Invalid fame list</Error>"); break; } string ac = "FALSE"; if (Query["accountId"] != null) { ac = "(accId=@accId AND chrId=@charId)"; } if (status == null) { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("FameList"); XmlAttribute spanAttr = doc.CreateAttribute("timespan"); spanAttr.Value = Query["timespan"]; root.Attributes.Append(spanAttr); doc.AppendChild(root); using (Database db = new Database()) { MySqlCommand cmd = db.CreateQuery(); cmd.CommandText = @"SELECT * FROM death WHERE " + span + @" OR " + ac + @" ORDER BY totalFame DESC LIMIT 20;"; if (Query["accountId"] != null) { cmd.Parameters.AddWithValue("@accId", Query["accountId"]); cmd.Parameters.AddWithValue("@charId", Query["charId"]); } using (MySqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { XmlElement elem = doc.CreateElement("FameListElem"); int accId = rdr.GetInt32("accId"); XmlAttribute accIdAttr = doc.CreateAttribute("accountId"); accIdAttr.Value = accId.ToString(); elem.Attributes.Append(accIdAttr); XmlAttribute chrIdAttr = doc.CreateAttribute("charId"); chrIdAttr.Value = rdr.GetInt32("chrId").ToString(); elem.Attributes.Append(chrIdAttr); root.AppendChild(elem); XmlElement nameElem = doc.CreateElement("Name"); nameElem.InnerText = String.Empty; elem.AppendChild(nameElem); XmlElement objTypeElem = doc.CreateElement("ObjectType"); objTypeElem.InnerText = rdr.GetString("charType"); elem.AppendChild(objTypeElem); XmlElement tex1Elem = doc.CreateElement("Tex1"); tex1Elem.InnerText = rdr.GetString("tex1"); elem.AppendChild(tex1Elem); XmlElement tex2Elem = doc.CreateElement("Tex2"); tex2Elem.InnerText = rdr.GetString("tex2"); elem.AppendChild(tex2Elem); XmlElement skinElem = doc.CreateElement("Texture"); skinElem.InnerText = rdr.GetString("skin"); elem.AppendChild(skinElem); XmlElement equElem = doc.CreateElement("Equipment"); string beforeItems = rdr.GetString("items"); List <int> Items = new List <int>(); foreach (int code in Utils.FromCommaSepString32(beforeItems)) { Item item = null; using (Database db2 = new Database()) item = db2.getSerialInfo(code, Program.GameData); if (item != null) { Items.Add(item.ObjectType); } else { Items.Add(-1); } } equElem.InnerText = Utils.GetCommaSepString(Items.ToArray()); elem.AppendChild(equElem); XmlElement fameElem = doc.CreateElement("TotalFame"); fameElem.InnerText = rdr.GetString("totalFame"); elem.AppendChild(fameElem); } } XmlNodeList list = doc.SelectNodes("/FameList/FameListElem"); foreach (XmlNode node in list) { foreach (XmlNode xnode in node.ChildNodes) { if (xnode.Name == "Name") { xnode.InnerText = db.GetAccount(node.Attributes["accountId"].Value, Program.GameData).Name; } } } } XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; using (XmlWriter wtr = XmlWriter.Create(Context.Response.OutputStream)) doc.Save(wtr); } }
public void XmlDsigXPathWithNamespacesTransformExplicitNamespaceRoundTripTest() { RSACryptoServiceProvider key = new RSACryptoServiceProvider(); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(RawXml); SignedXml signer = new SignedXml(doc); Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); Dictionary <string, string> explicitNamespaces = new Dictionary <string, string>(); explicitNamespaces["clrsec"] = "http://www.codeplex.com/clrsecurity"; reference.AddTransform(new XmlDsigXPathWithNamespacesTransform("ancestor-or-self::node()[@clrsec:sign='true']", explicitNamespaces)); signer.AddReference(reference); signer.SigningKey = key; signer.ComputeSignature(); XmlElement signature = signer.GetXml(); doc.DocumentElement.AppendChild(signature); // Now try to verify - this will use the built in XPath transform to do the verification, since // we have to modify machine.config to use custom transforms. SignedXml verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsTrue(verifier.CheckSignature(key)); // We should also be able to verify the signature after modifying the unsignedNode node, // since the XPath should have excluded it. XmlElement unsigned = doc.GetElementsByTagName("unsignedNode")[0] as XmlElement; XmlAttribute unsignedAttr = doc.CreateAttribute("state"); unsignedAttr.Value = "unsigned"; unsigned.Attributes.Append(unsignedAttr); verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsTrue(verifier.CheckSignature(key)); // Modifying the signedNode should also be allowed, since it is not using a clrsec:sign attribute XmlElement signed = doc.GetElementsByTagName("signedNode")[0] as XmlElement; XmlAttribute unsignedAttr2 = doc.CreateAttribute("state"); unsignedAttr2.Value = "unsigned"; unsigned.Attributes.Append(unsignedAttr2); verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsTrue(verifier.CheckSignature(key)); // However, we should not be able to modify the signedNode node XmlElement signedNamespace = doc.GetElementsByTagName("signedNamespaceNode", "http://www.codeplex.com/clrsecurity")[0] as XmlElement; XmlAttribute signedAttr = doc.CreateAttribute("state"); signedAttr.Value = "signed"; signedNamespace.Attributes.Append(signedAttr); verifier = new SignedXml(doc); verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement); Assert.IsFalse(verifier.CheckSignature(key)); }
private void Init_Data() { this.type_ = new Dictionary <string, AsmTokenType>(); this.arch_ = new Dictionary <string, Arch>(); this.assembler_ = new Dictionary <string, AssemblerEnum>(); this.description_ = new Dictionary <string, string>(); // fill the dictionary with keywords XmlDocument xmlDoc = this.Get_Xml_Data(); foreach (XmlNode node in xmlDoc.SelectNodes("//misc")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found misc with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.Misc; this.arch_[name] = Retrieve_Arch(node); this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//directive")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found directive with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.Directive; this.arch_[name] = Retrieve_Arch(node); this.assembler_[name] = Retrieve_Assembler(node); this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//register")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found register with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); //this._type[name] = AsmTokenType.Register; this.arch_[name] = Retrieve_Arch(node); this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//userdefined1")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found userdefined1 with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.UserDefined1; this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//userdefined2")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found userdefined2 with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.UserDefined2; this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//userdefined3")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found userdefined3 with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.UserDefined3; this.description_[name] = Retrieve_Description(node); } } }
public static List<Perk> Load(){ XmlDocument xmlDoc = new XmlDocument(); GameObject obj=Resources.Load("IconList", typeof(GameObject)) as GameObject; IconList iconList=obj.GetComponent<IconList>(); TextAsset perkTextAsset=Resources.Load("Perk", typeof(TextAsset)) as TextAsset; if(perkTextAsset!=null){ xmlDoc.Load(new MemoryStream(perkTextAsset.bytes)); XmlNode rootNode = xmlDoc.FirstChild; if (rootNode.Name == "something"){ int perkCount=rootNode.ChildNodes.Count; allPerkList=new List<Perk>(); for(int n=0; n<perkCount; n++){ allPerkList.Add(new Perk()); Perk perk=allPerkList[n]; for(int m=0; m<rootNode.ChildNodes[n].Attributes.Count; m++){ XmlAttribute attr=rootNode.ChildNodes[n].Attributes[m]; if(attr.Name=="ID"){ perk.ID=int.Parse(attr.Value); } else if(attr.Name=="icon"){ int ID=int.Parse(attr.Value); if(iconList.perkIconList.Count>ID) perk.icon=iconList.perkIconList[ID]; } else if(attr.Name=="iconUL"){ int ID=int.Parse(attr.Value); if(iconList.perkIconList.Count>ID) perk.iconUnlocked=iconList.perkIconList[ID]; } else if(attr.Name=="iconUA"){ int ID=int.Parse(attr.Value); if(iconList.perkIconList.Count>ID) perk.iconUnavailable=iconList.perkIconList[ID]; //~ string icon=attr.Value; //~ perk.iconUnavailable=Resources.Load("PerkIcons/"+icon, typeof(Texture)) as Texture; } else if(attr.Name=="name"){ perk.name=attr.Value; } else if(attr.Name=="type"){ perk.SetType((_PerkType)int.Parse(attr.Value)); } else if(attr.Name=="waveMin"){ perk.waveMin=int.Parse(attr.Value); } else if(attr.Name=="perkMin"){ perk.perkMin=int.Parse(attr.Value); } else if(attr.Name=="modTypeVal"){ perk.modTypeVal=(_ModifierType)int.Parse(attr.Value); } else if(attr.Name=="modTypeRsc"){ perk.modTypeRsc=(_ModifierType)int.Parse(attr.Value); } else if(attr.Name=="valueCount"){ int count=int.Parse(attr.Value); perk.valueCount=count; perk.value=new float[count]; for(int i=m; i<m+count; i++){ perk.value[i-m]=float.Parse(rootNode.ChildNodes[n].Attributes[i+1].Value.ToString()); } } else if(attr.Name=="desp"){ perk.desp=attr.Value; } else if(attr.Name=="towerID"){ perk.towerID=int.Parse(attr.Value); } else if(attr.Name=="abilityID"){ perk.abilityID=int.Parse(attr.Value); } else if(attr.Name=="enableASID"){ int val=int.Parse(attr.Value); if(val==1) perk.enableAbilityS=true; else perk.enableAbilityS=false; } else if(attr.Name=="abilitySID"){ perk.abilitySID=int.Parse(attr.Value); } else if(attr.Name=="abilityGCount"){ int count=int.Parse(attr.Value); perk.abilityGroup=new List<int>(); for(int i=m; i<m+count; i++){ perk.abilityGroup.Add(int.Parse(rootNode.ChildNodes[n].Attributes[i+1].Value)); } } else if(attr.Name=="repeat"){ int val=int.Parse(attr.Value); if(val==1) perk.repeatable=true; else perk.repeatable=false; } else if(attr.Name=="rscCount"){ int count=int.Parse(attr.Value); perk.rsc=new float[count]; for(int i=m; i<m+count; i++){ perk.rsc[i-m]=float.Parse(rootNode.ChildNodes[n].Attributes[i+1].Value); } } else if(attr.Name=="costCount"){ int count=int.Parse(attr.Value); perk.costs=new int[count]; for(int i=m; i<m+count; i++){ perk.costs[i-m]=int.Parse(rootNode.ChildNodes[n].Attributes[i+1].Value); } } else if(attr.Name=="prereqCount"){ int count=int.Parse(attr.Value); for(int i=m; i<m+count; i++){ perk.prereq.Add(int.Parse(rootNode.ChildNodes[n].Attributes[i+1].Value)); } } } } } } for(int i=0; i<allPerkList.Count; i++){ //allPerkList[i].ID=i; perkIDList.Add(allPerkList[i].ID); } return allPerkList; }
protected override void ProcessRecord() { XmlDocument doc = new XmlDocument(); doc.Load(this.SchemaLocation); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("xs", SchemaNamespace); bool changedSchema = false; var choiceNodes = doc.SelectNodes("//xs:choice", nsManager); foreach (XmlElement choiceElement in choiceNodes) { bool foundNonElement = false; List <string[]> elementNameWords = new List <string[]>(); foreach (XmlElement childNode in choiceElement.ChildNodes) { if (childNode.LocalName == "annotation") { continue; } if (childNode.LocalName != "element" || childNode.Attributes["name"] == null) { foundNonElement = true; break; } string[] nameWords = Shared.Helper.GetWords(childNode.Attributes["name"].Value); elementNameWords.Add(nameWords); } if (foundNonElement) { continue; } string commonName = Shared.Helper.FindCommonWord(elementNameWords); if (string.IsNullOrEmpty(commonName)) { continue; } commonName = commonName + "[x]"; XmlElement annotationElement = choiceElement.SelectSingleNode("xs:annotation", nsManager) as XmlElement; if (annotationElement == null) { annotationElement = doc.CreateElement("xs", "annotation", SchemaNamespace); if (choiceElement.ChildNodes.Count > 0) { choiceElement.InsertBefore(annotationElement, choiceElement.FirstChild); } else { choiceElement.AppendChild(annotationElement); } } string appInfoXpath = "xs:appinfo[@source='" + AppInfoSource + "']"; XmlElement appInfoElement = annotationElement.SelectSingleNode(appInfoXpath, nsManager) as XmlElement; if (appInfoElement == null) { appInfoElement = doc.CreateElement("xs", "appinfo", SchemaNamespace); XmlAttribute sourceAttribute = doc.CreateAttribute("source"); sourceAttribute.Value = AppInfoSource; appInfoElement.Attributes.Append(sourceAttribute); if (annotationElement.ChildNodes.Count > 0) { annotationElement.InsertBefore(appInfoElement, annotationElement.FirstChild); } else { annotationElement.AppendChild(appInfoElement); } appInfoElement.InnerText = commonName; changedSchema = true; } } if (changedSchema) { doc.Save(this.SchemaLocation); } }
private static Timecode GetTimecode(XmlAttribute valueAttribute) { double seconds = Double.Parse(valueAttribute.Value, CultureInfo.InvariantCulture); return Timecode.FromSeconds(seconds); }
void SaveToXML(){ Debug.Log("writing..."); GameObject obj=Resources.Load("IconList", typeof(GameObject)) as GameObject; IconList iconList=obj.GetComponent<IconList>(); iconList.perkIconList=new List<Texture>(); XmlDocument xmlDoc=new XmlDocument(); xmlDoc.LoadXml("<something></something>"); for(int j=0; j<allPerkList.Count; j++){ Perk perk=allPerkList[j]; XmlNode docRoot = xmlDoc.DocumentElement; XmlElement perkEle = xmlDoc.CreateElement("Perk"+j.ToString()); XmlAttribute Attr = xmlDoc.CreateAttribute("ID"); Attr.Value = perk.ID.ToString(); perkEle.Attributes.Append(Attr); XmlAttribute Attr1 = xmlDoc.CreateAttribute("name"); XmlAttribute Attr2 = xmlDoc.CreateAttribute("type"); XmlAttribute Attr3 = xmlDoc.CreateAttribute("waveMin"); XmlAttribute Attr4 = xmlDoc.CreateAttribute("perkMin"); XmlAttribute Attr5 = xmlDoc.CreateAttribute("modTypeVal"); XmlAttribute Attr6 = xmlDoc.CreateAttribute("modTypeRsc"); XmlAttribute Attr8 = xmlDoc.CreateAttribute("repeat"); Attr1.Value = perk.name.ToString(); Attr2.Value = ((int)perk.type).ToString(); Attr3.Value = perk.waveMin.ToString(); Attr4.Value = perk.perkMin.ToString(); Attr5.Value = ((int)perk.modTypeVal).ToString(); Attr6.Value = ((int)perk.modTypeRsc).ToString(); Attr8.Value = (perk.repeatable ? 1 : 0).ToString(); perkEle.Attributes.Append(Attr1); perkEle.Attributes.Append(Attr2); perkEle.Attributes.Append(Attr3); perkEle.Attributes.Append(Attr4); perkEle.Attributes.Append(Attr5); perkEle.Attributes.Append(Attr6); perkEle.Attributes.Append(Attr8); if(perk.valueCount>0){ XmlAttribute valCount = xmlDoc.CreateAttribute("valueCount"); valCount.Value = perk.value.Length.ToString(); perkEle.Attributes.Append(valCount); XmlAttribute[] attrVal = new XmlAttribute[perk.value.Length]; for(int i=0; i<perk.value.Length; i++){ attrVal[i]=xmlDoc.CreateAttribute("val"+i.ToString()); attrVal[i].Value=perk.value[i].ToString(); perkEle.Attributes.Append(attrVal[i]); } } if(perk.icon!=null){ int ID=0; if(!iconList.perkIconList.Contains(perk.icon)){ iconList.perkIconList.Add(perk.icon); ID=iconList.perkIconList.Count-1; } else ID=iconList.perkIconList.IndexOf(perk.icon); XmlAttribute AttrIcon = xmlDoc.CreateAttribute("icon"); AttrIcon.Value = (ID).ToString(); perkEle.Attributes.Append(AttrIcon); } if(perk.iconUnavailable!=null){ int ID=0; if(!iconList.perkIconList.Contains(perk.iconUnavailable)){ iconList.perkIconList.Add(perk.iconUnavailable); ID=iconList.perkIconList.Count-1; } else ID=iconList.perkIconList.IndexOf(perk.iconUnavailable); XmlAttribute AttrIcon = xmlDoc.CreateAttribute("iconUA"); AttrIcon.Value = (ID).ToString(); perkEle.Attributes.Append(AttrIcon); } if(perk.iconUnlocked!=null){ //~ string sourcePath=AssetDatabase.GetAssetPath(perk.iconUnlocked); //~ string targetPath=Application.dataPath + "/TDTK/Resources/PerkIcons/"; //~ if(Resources.Load("PerkIcons/"+perk.iconUnlocked.name, typeof(Texture))==null) //~ AssetDatabase.CopyAsset(sourcePath, targetPath); //~ XmlAttribute AttrIcon = xmlDoc.CreateAttribute("iconUL"); //~ AttrIcon.Value = (perk.iconUnlocked.name).ToString(); //~ perkEle.Attributes.Append(AttrIcon); int ID=0; if(!iconList.perkIconList.Contains(perk.iconUnlocked)){ iconList.perkIconList.Add(perk.iconUnlocked); ID=iconList.perkIconList.Count-1; } else ID=iconList.perkIconList.IndexOf(perk.iconUnlocked); XmlAttribute AttrIcon = xmlDoc.CreateAttribute("iconUL"); AttrIcon.Value = (ID).ToString(); perkEle.Attributes.Append(AttrIcon); } if(perk.enableTower){ XmlAttribute AttrTID = xmlDoc.CreateAttribute("towerID"); AttrTID.Value = perk.towerID.ToString(); perkEle.Attributes.Append(AttrTID); } if(perk.enableAbility){ XmlAttribute AttrAID = xmlDoc.CreateAttribute("abilityID"); AttrAID.Value = perk.abilityID.ToString(); perkEle.Attributes.Append(AttrAID); } if(perk.enableAbilityS){ XmlAttribute AttrASIDF = xmlDoc.CreateAttribute("enableASID"); AttrASIDF.Value = (perk.enableAbilityS ? 1 : 0).ToString(); perkEle.Attributes.Append(AttrASIDF); XmlAttribute AttrASID = xmlDoc.CreateAttribute("abilitySID"); AttrASID.Value = perk.abilitySID.ToString(); perkEle.Attributes.Append(AttrASID); } if(perk.enableAbilityGroup){ XmlAttribute attrAbilCount = xmlDoc.CreateAttribute("abilityGCount"); attrAbilCount.Value = perk.abilityGroup.Count.ToString(); perkEle.Attributes.Append(attrAbilCount); XmlAttribute[] attrAbil = new XmlAttribute[perk.abilityGroup.Count]; for(int i=0; i<perk.abilityGroup.Count; i++){ attrAbil[i]=xmlDoc.CreateAttribute("abil"+i.ToString()); attrAbil[i].Value=perk.abilityGroup[i].ToString(); perkEle.Attributes.Append(attrAbil[i]); } } if(perk.enableRsc){ XmlAttribute attrRscCount = xmlDoc.CreateAttribute("rscCount"); attrRscCount.Value = perk.rsc.Length.ToString(); perkEle.Attributes.Append(attrRscCount); XmlAttribute[] attrRsc = new XmlAttribute[perk.rsc.Length]; for(int i=0; i<perk.rsc.Length; i++){ attrRsc[i]=xmlDoc.CreateAttribute("rsc"+i.ToString()); attrRsc[i].Value=perk.rsc[i].ToString(); perkEle.Attributes.Append(attrRsc[i]); } } XmlAttribute attrCostCount = xmlDoc.CreateAttribute("costCount"); attrCostCount.Value = perk.costs.Length.ToString(); perkEle.Attributes.Append(attrCostCount); XmlAttribute[] attrCost = new XmlAttribute[perk.costs.Length]; for(int i=0; i<perk.costs.Length; i++){ attrCost[i]=xmlDoc.CreateAttribute("cost"+i.ToString()); attrCost[i].Value=perk.costs[i].ToString(); perkEle.Attributes.Append(attrCost[i]); } XmlAttribute attrPrereqCount = xmlDoc.CreateAttribute("prereqCount"); attrPrereqCount.Value = perk.prereq.Count.ToString(); perkEle.Attributes.Append(attrPrereqCount); XmlAttribute[] attrPrereq = new XmlAttribute[perk.prereq.Count]; for(int i=0; i<perk.prereq.Count; i++){ attrPrereq[i]=xmlDoc.CreateAttribute("prereq"+i.ToString()); attrPrereq[i].Value=perk.prereq[i].ToString(); perkEle.Attributes.Append(attrPrereq[i]); } XmlAttribute attrDesp = xmlDoc.CreateAttribute("desp"); attrDesp.Value = perk.desp.ToString(); perkEle.Attributes.Append(attrDesp); docRoot.AppendChild(perkEle); } //~ if(Application.platform == RuntimePlatform.OSXEditor){ xmlDoc.Save(Application.dataPath + "/TDTK/Resources/Perk.txt"); //~ } //~ else if (Application.platform == RuntimePlatform.WindowsEditor){ //~ xmlDoc.Save(Application.dataPath + "\\TDTK\\Resources\\Perk.txt"); //~ } EditorUtility.SetDirty(iconList); AssetDatabase.Refresh(); if(onPerksUpdateE!=null) onPerksUpdateE(); Debug.Log("done"); }
public void AddAttributeObjectBinding(XmlAttribute attribute) { this.attributeObjectBindings.RemoveAll(e => ReferenceEquals(e.BindingObject.GetType(), attribute.BindingObject.GetType())); this.attributeObjectBindings.Add(attribute); }
/** * Bir eke iliskin ardisil ekler belirlenir. ardisil ekler * a) ek kumelerinden * b) normal tek olarak * c) dogrudan baska bir ekin ardisil eklerinden kopyalanarak * elde edilir. * Ayrica eger oncelikli ekler belirtilmis ise bu ekler ardisil ek listeisnin en basina koyulur. * * @param ekElement : ek xml bileseni.. * @return Ek referans Listesi. * @param anaEk ardisil ekler eklenecek asil ek */ private List <Ek> ardisilEkleriOlustur(Ek anaEk, XmlElement ekElement) { Set <Ek> ardisilEkSet = new HashedSet <Ek>(); XmlElement ardisilEklerEl = (XmlElement)ekElement.SelectNodes("ardisil-ekler")[0]; if (ardisilEklerEl == null) { return(new List <Ek>()); } // tek ekleri ekle. XmlNodeList tekArdisilEkler = ardisilEklerEl.SelectNodes("aek"); foreach (XmlElement element in tekArdisilEkler) { String ekAdi = element.InnerText; Ek ek = this.ekler[ekAdi]; if (ek == null) { exit(anaEk.ad() + " icin ardisil ek bulunamiyor! " + ekAdi); } ardisilEkSet.Add(ek); } // kume eklerini ekle. XmlNodeList kumeEkler = ardisilEklerEl.SelectNodes("kume"); foreach (XmlElement element in kumeEkler) { String kumeAdi = element.InnerText; Set <Ek> kumeEkleri = ekKumeleri[kumeAdi]; if (kumeEkleri == null) { exit("kume bulunamiyor..." + kumeAdi); } ardisilEkSet.AddAll(kumeEkleri); } //varsa baska bir ekin ardisil eklerini kopyala. XmlAttribute attr = ardisilEklerEl.GetAttributeNode("kopya-ek"); if (attr != null) { String kopyaEkadi = attr.Value; Ek ek = this.ekler[kopyaEkadi]; if (ek == null) { exit(anaEk.ad() + " icin kopyalanacak ek bulunamiyor! " + kopyaEkadi); } ardisilEkSet.AddAll(ek.ardisilEkler()); } List <Ek> ardisilEkler = new List <Ek>(ardisilEkSet.Count); //varsa oncelikli ekleri oku ve ardisil ekler listesinin ilk basina koy. // bu tamamen performans ile iliskili bir islemdir. XmlElement oncelikliEklerEl = (XmlElement)ekElement.SelectNodes("oncelikli-ekler")[0]; if (oncelikliEklerEl != null) { XmlNodeList oncelikliEkler = oncelikliEklerEl.SelectNodes("oek"); foreach (XmlElement element in oncelikliEkler) { String ekAdi = element.InnerText; Ek ek = this.ekler[ekAdi]; if (ek == null) { exit(anaEk.ad() + " icin oncelikli ek bulunamiyor! " + ekAdi); } if (ardisilEkSet.Contains(ek)) { ardisilEkler.Add(ek); ardisilEkSet.Remove(ek); } else { logger.Warn(anaEk.ad() + "icin oncelikli ek:" + ekAdi + " bu ekin ardisil eki degil!"); } } } ardisilEkler.AddRange(ardisilEkSet); return(ardisilEkler); }
public static XmlElement gWell2 (XmlDocument svgDoc, string sJH, int iXview, int iYview, int iWellType, int JHFontSize, int radis, int iCirlceWidth, int DX_JHText, int DY_JHText) { XmlElement gWell = svgDoc.CreateElement("g"); XmlElement wellRect = svgDoc.CreateElement("rect"); wellRect.SetAttribute("x", (iXview - radis / 2).ToString()); wellRect.SetAttribute("y", (iYview - radis / 2).ToString()); wellRect.SetAttribute("width", radis.ToString()); wellRect.SetAttribute("height", radis.ToString("0")); wellRect.SetAttribute("id", sJH); wellRect.SetAttribute("style", "stroke-width:1"); wellRect.SetAttribute("stroke", "black"); wellRect.SetAttribute("fill", "none"); wellRect.SetAttribute("onclick", "getID(evt)"); string m_colorWell = "none"; if (iWellType == 3) { m_colorWell = "red"; } else if (iWellType == 1) { XmlElement gWellSymbolUse = svgDoc.CreateElement("use"); gWellSymbolUse.SetAttribute("x", iXview.ToString()); gWellSymbolUse.SetAttribute("y", iYview.ToString()); XmlAttribute WellSymbolNode = svgDoc.CreateAttribute("xlink", "href", "http://www.w3.org/1999/xlink"); WellSymbolNode.Value = "#" + "idOilGasWellSymbol"; gWellSymbolUse.Attributes.Append(WellSymbolNode); gWell.AppendChild(gWellSymbolUse); m_colorWell = "red"; } else if (iWellType == 5) { m_colorWell = "Gold"; } else if (iWellType == 15) { XmlElement gWellSymbolUse = svgDoc.CreateElement("use"); gWellSymbolUse.SetAttribute("x", iXview.ToString()); gWellSymbolUse.SetAttribute("y", iYview.ToString()); XmlAttribute WellSymbolNode = svgDoc.CreateAttribute("xlink", "href", "http://www.w3.org/1999/xlink"); WellSymbolNode.Value = "#" + "InjectWellSymbol"; gWellSymbolUse.Attributes.Append(WellSymbolNode); gWell.AppendChild(gWellSymbolUse); m_colorWell = "blue"; } else if (iWellType == 8) { XmlElement gWellSymbolUse = svgDoc.CreateElement("use"); gWellSymbolUse.SetAttribute("x", iXview.ToString()); gWellSymbolUse.SetAttribute("y", iYview.ToString()); XmlAttribute WellSymbolNode = svgDoc.CreateAttribute("xlink", "href", "http://www.w3.org/1999/xlink"); WellSymbolNode.Value = "#" + "idPlatformWell"; gWellSymbolUse.Attributes.Append(WellSymbolNode); gWell.AppendChild(gWellSymbolUse); m_colorWell = "red"; } else { m_colorWell = "black"; XmlElement gWellSymbolInner = svgDoc.CreateElement("circle"); gWellSymbolInner.SetAttribute("x", iXview.ToString()); gWellSymbolInner.SetAttribute("y", iYview.ToString()); gWellSymbolInner.SetAttribute("r", "1.5"); gWellSymbolInner.SetAttribute("stroke", m_colorWell); gWellSymbolInner.SetAttribute("stroke-width", iCirlceWidth.ToString()); gWellSymbolInner.SetAttribute("fill", "none"); gWell.AppendChild(gWellSymbolInner); } XmlElement gWellSymbol = svgDoc.CreateElement("circle"); gWellSymbol.SetAttribute("cx", iXview.ToString()); gWellSymbol.SetAttribute("cy", iYview.ToString()); gWellSymbol.SetAttribute("r", radis.ToString()); gWellSymbol.SetAttribute("stroke", m_colorWell); gWellSymbol.SetAttribute("stroke-width", iCirlceWidth.ToString()); gWellSymbol.SetAttribute("fill", "none"); gWell.AppendChild(gWellSymbol); XmlElement gJHText = svgDoc.CreateElement("text"); gJHText.SetAttribute("x", (iXview - DX_JHText).ToString()); gJHText.SetAttribute("y", (iYview + DX_JHText).ToString()); gJHText.SetAttribute("font-size", JHFontSize.ToString()); gJHText.SetAttribute("font-style", "normal"); gJHText.InnerText = sJH; gJHText.SetAttribute("fill", m_colorWell); gWell.AppendChild(gJHText); return(gWell); }
/// <summary> /// Creates complex XML nodes /// </summary> /// <remarks> /// 1. "d:conditionalFormatting" /// 1.1. Creates/find the first "conditionalFormatting" node /// /// 2. "d:conditionalFormatting/@sqref" /// 2.1. Creates/find the first "conditionalFormatting" node /// 2.2. Creates (if not exists) the @sqref attribute /// /// 3. "d:conditionalFormatting/@id='7'/@sqref='A9:B99'" /// 3.1. Creates/find the first "conditionalFormatting" node /// 3.2. Creates/update its @id attribute to "7" /// 3.3. Creates/update its @sqref attribute to "A9:B99" /// /// 4. "d:conditionalFormatting[@id='7']/@sqref='X1:X5'" /// 4.1. Creates/find the first "conditionalFormatting" node with @id=7 /// 4.2. Creates/update its @sqref attribute to "X1:X5" /// /// 5. "d:conditionalFormatting[@id='7']/@id='8'/@sqref='X1:X5'/d:cfRule/@id='AB'" /// 5.1. Creates/find the first "conditionalFormatting" node with @id=7 /// 5.2. Set its @id attribute to "8" /// 5.2. Creates/update its @sqref attribute and set it to "X1:X5" /// 5.3. Creates/find the first "cfRule" node (inside the node) /// 5.4. Creates/update its @id attribute to "AB" /// /// 6. "d:cfRule/@id=''" /// 6.1. Creates/find the first "cfRule" node /// 6.1. Remove the @id attribute /// </remarks> /// <param name="topNode"></param> /// <param name="path"></param> /// <param name="nodeInsertOrder"></param> /// <param name="referenceNode"></param> /// <returns>The last node creates/found</returns> internal XmlNode CreateComplexNode( XmlNode topNode, string path, eNodeInsertOrder nodeInsertOrder, XmlNode referenceNode) { // Path is obrigatory if ((path == null) || (path == string.Empty)) { return topNode; } XmlNode node = topNode; string nameSpaceURI = string.Empty; //TODO: BUG: when the "path" contains "/" in an attrribue value, it gives an error. // Separate the XPath to Nodes and Attributes foreach (string subPath in path.Split('/')) { // The subPath can be any one of those: // nodeName // x:nodeName // nodeName[find criteria] // x:nodeName[find criteria] // @attribute // @attribute='attribute value' // Check if the subPath has at least one character if (subPath.Length > 0) { // Check if the subPath is an attribute (with or without value) if (subPath.StartsWith("@")) { // @attribute --> Create attribute // @attribute='' --> Remove attribute // @attribute='attribute value' --> Create attribute + update value string[] attributeSplit = subPath.Split('='); string attributeName = attributeSplit[0].Substring(1, attributeSplit[0].Length - 1); string attributeValue = null; // Null means no attribute value // Check if we have an attribute value to set if (attributeSplit.Length > 1) { // Remove the ' or " from the attribute value attributeValue = attributeSplit[1].Replace("'", "").Replace("\"", ""); } // Get the attribute (if exists) XmlAttribute attribute = (XmlAttribute)(node.Attributes.GetNamedItem(attributeName)); // Remove the attribute if value is empty (not null) if (attributeValue == string.Empty) { // Only if the attribute exists if (attribute != null) { node.Attributes.Remove(attribute); } } else { // Create the attribue if does not exists if (attribute == null) { // Create the attribute attribute = node.OwnerDocument.CreateAttribute( attributeName); // Add it to the current node node.Attributes.Append(attribute); } // Update the attribute value if (attributeValue != null) { node.Attributes[attributeName].Value = attributeValue; } } } else { // nodeName // x:nodeName // nodeName[find criteria] // x:nodeName[find criteria] // Look for the node (with or without filter criteria) XmlNode subNode = node.SelectSingleNode(subPath, NameSpaceManager); // Check if the node does not exists if (subNode == null) { string nodeName; string nodePrefix; string[] nameSplit = subPath.Split(':'); nameSpaceURI = string.Empty; // Check if the name has a prefix like "d:nodeName" if (nameSplit.Length > 1) { nodePrefix = nameSplit[0]; nameSpaceURI = NameSpaceManager.LookupNamespace(nodePrefix); nodeName = nameSplit[1]; } else { nodePrefix = string.Empty; nameSpaceURI = string.Empty; nodeName = nameSplit[0]; } // Check if we have a criteria part in the node name if (nodeName.IndexOf("[") > 0) { // remove the criteria from the node name nodeName = nodeName.Substring(0, nodeName.IndexOf("[")); } if (nodePrefix == string.Empty) { subNode = node.OwnerDocument.CreateElement(nodeName, nameSpaceURI); } else { if (node.OwnerDocument != null && node.OwnerDocument.DocumentElement != null && node.OwnerDocument.DocumentElement.NamespaceURI == nameSpaceURI && node.OwnerDocument.DocumentElement.Prefix == string.Empty) { subNode = node.OwnerDocument.CreateElement( nodeName, nameSpaceURI); } else { subNode = node.OwnerDocument.CreateElement( nodePrefix, nodeName, nameSpaceURI); } } // Check if we need to use the "SchemaOrder" if (nodeInsertOrder == eNodeInsertOrder.SchemaOrder) { // Check if the Schema Order List is empty if ((SchemaNodeOrder == null) || (SchemaNodeOrder.Length == 0)) { // Use the "Insert Last" option when Schema Order List is empty nodeInsertOrder = eNodeInsertOrder.Last; } else { // Find the prepend node in order to insert referenceNode = GetPrependNode(nodeName, node); if (referenceNode != null) { nodeInsertOrder = eNodeInsertOrder.Before; } else { nodeInsertOrder = eNodeInsertOrder.Last; } } } switch (nodeInsertOrder) { case eNodeInsertOrder.After: node.InsertAfter(subNode, referenceNode); referenceNode = null; break; case eNodeInsertOrder.Before: node.InsertBefore(subNode, referenceNode); referenceNode = null; break; case eNodeInsertOrder.First: node.PrependChild(subNode); break; case eNodeInsertOrder.Last: node.AppendChild(subNode); break; } } // Make the newly created node the top node when the rest of the path // is being evaluated. So newly created nodes will be the children of the // one we just created. node = subNode; } } } // Return the last created/found node return node; }
private void WriteCurrentTextSegment(List <FcpXmlStyle> styles, Dictionary <int, string> styleTextPairs, XmlNode video, int number, string title, XmlDocument xml) { string xmlClipStructure = "<title name=\"Basic Title: [TITLEID]\" lane=\"1\" offset=\"8665300/2400s\" ref=\"r2\" duration=\"13400/2400s\" start=\"3600s\">" + Environment.NewLine + " <param name=\"Position\" key=\"9999/999166631/999166633/1/100/101\" value=\"-1.67499 -470.934\"/>" + Environment.NewLine + " <text>" + Environment.NewLine + //" <text-style ref=\"ts[NUMBER]\">THE NOISEMAKER</text-style>" + Environment.NewLine + " </text>" + Environment.NewLine + //" <text-style-def id=\"ts[NUMBER]\">" + Environment.NewLine + //" <text-style font=\"[FONT_NAME]\" fontSize=\"[FONT_SIZE]\" fontFace=\"[FONT_FACE]\" fontColor=\"[FONT_COLOR]\" baseline=\"[BASELINE]\" shadowColor=\"0 0 0 1\" shadowOffset=\"5 315\" alignment=\"center\"/>" + Environment.NewLine + //" </text-style-def>" + Environment.NewLine + "</title>"; var textStyleStructure = "<text-style font=\"[FONT_NAME]\" fontSize=\"[FONT_SIZE]\" fontFace=\"[FONT_FACE]\" fontColor=\"[FONT_COLOR]\" baseline=\"[BASELINE]\" shadowColor=\"0 0 0 1\" shadowOffset=\"5 315\" alignment=\"[ALIGNMENT]\" [ITALIC] [BOLD] />"; string temp = xmlClipStructure.Replace("[TITLEID]", title); video.InnerXml = temp; var titleNode = video.SelectSingleNode("//title"); var textNode = video.SelectSingleNode("//text"); var styleCount = 1; foreach (var pair in styleTextPairs) { var id = "ts" + number + "-" + styleCount; XmlNode textStyleNode = xml.CreateElement("text-style"); XmlAttribute refAttribute = xml.CreateAttribute("ref"); refAttribute.InnerText = id; textStyleNode.Attributes.Append(refAttribute); textStyleNode.InnerText = pair.Value; textNode.AppendChild(textStyleNode); XmlNode styleNode = xml.CreateElement("text-style-def"); XmlAttribute idAttribute = xml.CreateAttribute("id"); idAttribute.InnerText = id; styleNode.Attributes.Append(idAttribute); var tempStr = textStyleStructure; if (styles[pair.Key].Italic) { tempStr = tempStr.Replace("[ITALIC]", "italic=\"1\""); } else { tempStr = tempStr.Replace(" [ITALIC]", string.Empty); } if (styles[pair.Key].Bold) { tempStr = tempStr.Replace("[BOLD]", "bold=\"1\""); } else { tempStr = tempStr.Replace(" [BOLD]", string.Empty); } styleNode.InnerXml = tempStr .Replace("[NUMBER]", number.ToString(CultureInfo.InvariantCulture) + "-" + styleCount) .Replace("[TITLEID]", title) .Replace("[FONT_NAME]", styles[pair.Key].FontName) .Replace("[FONT_SIZE]", styles[pair.Key].FontSize.ToString(CultureInfo.InvariantCulture)) .Replace("[FONT_FACE]", styles[pair.Key].FontFace) .Replace("[FONT_COLOR]", ToColorString(styles[pair.Key].FontColor)) .Replace("[ALIGNMENT]", styles[pair.Key].Alignment) .Replace("[BASELINE]", styles[pair.Key].Baseline.ToString(CultureInfo.InvariantCulture)); titleNode.AppendChild(styleNode); styleCount++; } }
internal override void ProcessAttribute(string prefix, string name, string ns, string value) { XmlQualifiedName qname = new XmlQualifiedName(name, ns); if (this.currentEntry.Attributes != null) { for (int i = 0; i < this.currentEntry.Attributes.Length; i++) { XsdAttributeEntry a = this.currentEntry.Attributes[i]; if (this.schemaNames.TokenToQName[(int)a.Attribute].Equals(qname)) { try { a.BuildFunc(this, value); } catch (XmlSchemaException e) { e.SetSource(this.reader.BaseURI, this.positionInfo.LineNumber, this.positionInfo.LinePosition); SendValidationEvent(Res.Sch_InvalidXsdAttributeDatatypeValue, new string[] {name, e.Message},XmlSeverityType.Error); } return; } } } // Check non-supported attribute if ((ns != this.schemaNames.NsXs) && (ns.Length != 0)) { if (ns == this.schemaNames.NsXmlNs) { if (this.namespaces == null) { this.namespaces = new Hashtable(); } this.namespaces.Add((name == this.schemaNames.QnXmlNs.Name) ? string.Empty : name, value); } else { XmlAttribute attribute = new XmlAttribute(prefix, name, ns, this.schema.Document); attribute.Value = value; this.unhandledAttributes.Add(attribute); } } else { SendValidationEvent(Res.Sch_UnsupportedAttribute, qname.ToString()); } }
/* Main NavBar */ protected void nbMenu_ItemDataBound(object source, DevExpress.Web.ASPxNavBar.NavBarItemEventArgs e) { e.Item.Name = e.Item.Text; IHierarchyData itemHierarchyData = (e.Item.DataItem as IHierarchyData); XmlElement xmlElement = itemHierarchyData.Item as XmlElement; if (xmlElement.Attributes["Caption"] != null) { e.Item.Name = xmlElement.Attributes["Caption"].Value; } if (string.IsNullOrEmpty(DemoName)) { this.demoName = "ASPxperience"; if (xmlElement.OwnerDocument.DocumentElement.Attributes["Name"] != null) { this.demoName = xmlElement.OwnerDocument.DocumentElement.Attributes["Name"].Value; } } if (GetUrl(e.Item.NavigateUrl).ToLower() == Request.AppRelativeCurrentExecutionFilePath.ToLower()) { if (Request.QueryString["Section"] != null) { if (xmlElement.Attributes["Section"] == null || Request.QueryString["Section"] != xmlElement.Attributes["Section"].Value) { return; } } e.Item.Selected = true; e.Item.Group.Expanded = true; XmlAttribute useFullTitle = xmlElement.Attributes["UseFullTitle"]; if (useFullTitle != null && !bool.Parse(useFullTitle.Value)) { if (xmlElement.Attributes["Title"] != null) { this.title = xmlElement.Attributes["Title"].Value; } } else { XmlNode xmlGroupNode = xmlElement.ParentNode; XmlNode xmlMainNode = xmlGroupNode.ParentNode; string titleFormatString = xmlMainNode.Attributes["TitleFormatString"] != null ? xmlMainNode.Attributes["TitleFormatString"].Value : ""; string mainTitle = xmlMainNode.Attributes["Title"] != null ? xmlMainNode.Attributes["Title"].Value : ""; string groupTitle = xmlGroupNode.Attributes["Title"] != null ? xmlGroupNode.Attributes["Title"].Value : ""; string demoTitle = xmlElement.Attributes["Title"] != null ? xmlElement.Attributes["Title"].Value : ""; if (string.IsNullOrEmpty(titleFormatString)) { if (!string.IsNullOrEmpty(mainTitle)) { titleFormatString = "{0}"; } if (!string.IsNullOrEmpty(groupTitle)) { titleFormatString += " - {1}"; } if (!string.IsNullOrEmpty(demoTitle)) { titleFormatString += " - {2}"; } } this.title = string.Format(titleFormatString, mainTitle, groupTitle, demoTitle); } foreach (XmlNode itemNode in xmlElement.ChildNodes) { switch (itemNode.Name) { case "Description": { this.description = itemNode.InnerXml; break; } case "GeneralTerms": { this.generalTerms = itemNode.InnerXml; if (itemNode.Attributes["ShowHeader"] != null && itemNode.Attributes["ShowHeader"].Value.ToLower() == "false") { this.showTermsHeader = false; } break; } } } } }
protected XmlNode LoadXmlString(string xml, string rootName = "root") { XmlReader xr = XmlReader.Create(new StringReader(xml)); root = null; parents.Clear(); while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && (xr.IsStartElement() || xr.IsEmptyElement)) { XmlNode node = parents.Count < 1 ? new XmlNode { Name = rootName } : root.New<XmlNode>(); node.Text = xr.Value; node.Name = xr.Name; node.NodeType = xr.NodeType; node.ValueType = xr.ValueType.FullName; if (xr.HasAttributes) { for (int i = 0; i < xr.AttributeCount; i++) { XmlAttribute att = new XmlAttribute(); xr.MoveToAttribute(i); att.Name = xr.Name; xr.GetAttribute(i); att.Text = xr.Value; node.Attributes.Add(att); } xr.MoveToElement(); } if (parents.Count < 1) { root = node; } else { parents.Peek().Add(node); } if (!xr.IsEmptyElement) { parents.Push(node); } if (OnReadStartElement != null) { OnReadStartElement(node); } } else if (xr.NodeType == XmlNodeType.Text || xr.NodeType == XmlNodeType.CDATA) { parents.Peek().Text = xr.Value; if (OnReadTextElement != null) { OnReadTextElement(parents.Peek()); } } else if (xr.NodeType == XmlNodeType.EndElement) { if (OnReadEndElement != null) { OnReadEndElement(parents.Peek()); } parents.Pop(); } } return root; }
public static void Import(string xmlPath, GameObject root, string materialFolder) { XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); XmlNode xmlRoot = doc.DocumentElement; XmlNodeList nodes = xmlRoot.SelectNodes("/assignments/node"); Dictionary <GameObject, List <Assignment> > allAssignments = new Dictionary <GameObject, List <Assignment> >(); foreach (XmlNode node in nodes) { string path = node.Attributes["path"].Value; XmlNodeList shaders = node.SelectNodes("shader"); foreach (XmlNode shader in shaders) { XmlAttribute name = shader.Attributes["name"]; XmlAttribute inst = shader.Attributes["instance"]; if (name == null) { continue; } int instNum = (inst == null ? 0 : Convert.ToInt32(inst.Value)); GameObject target = FindNode(root, path, instNum); if (target == null) { // Debug.Log("Could not find node: " + path); continue; } List <Assignment> assignments; if (!allAssignments.ContainsKey(target)) { assignments = new List <Assignment>(); allAssignments.Add(target, assignments); } else { assignments = allAssignments[target]; } Material material = GetMaterial(name.Value, materialFolder); if (material == null) { material = new Material(Shader.Find("Standard")); material.color = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); AssetDatabase.CreateAsset(material, materialFolder + "/" + name.Value + ".mat"); } // Get or create material assignment bool newlyAssigned = false; var a = new Assignment { material = material, faces = new List <int>() }; assignments.Add(a); newlyAssigned = true; string faceset = shader.InnerText; faceset.Trim(); if (faceset.Length > 0 && (newlyAssigned || a.faces.Count > 0)) { string[] items = faceset.Split(FaceSep, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < items.Length; ++i) { string[] rng = items[i].Split(RangeSep, StringSplitOptions.RemoveEmptyEntries); if (rng.Length == 1) { a.faces.Add(Convert.ToInt32(rng[0])); } else if (rng.Length == 2) { int j0 = Convert.ToInt32(rng[0]); int j1 = Convert.ToInt32(rng[1]); for (int j = j0; j <= j1; ++j) { a.faces.Add(j); } } } if (!newlyAssigned) { a.faces = new List <int>(new HashSet <int>(a.faces)); } } else if (faceset.Length == 0 && a.faces.Count > 0) { // Shader assgined to whole object, remove any face level assignments a.faces.Clear(); } } } // Update AlembicMaterial components foreach (KeyValuePair <GameObject, List <Assignment> > pair in allAssignments) { AlembicMaterial abcmaterial = pair.Key.GetComponent <AlembicMaterial>(); if (abcmaterial == null) { abcmaterial = pair.Key.AddComponent <AlembicMaterial>(); } abcmaterial.UpdateAssignments(pair.Value); } // Force refresh var player = root.GetComponent <AlembicStreamPlayer>(); if (player != null && player.Stream != null) { player.SendMessage("ForceRefresh", null, SendMessageOptions.DontRequireReceiver); } else { // todo: do figure something else... } }