public static void AddDocumentNode(XmlNode parent, ComponentRenderType outputType, string value) { XmlElement text = parent.OwnerDocument.CreateElement(UADataType.UAString.ToString()); text.InnerText = value; text.SetAttribute(DecoratorTags.OutputDecorator, ComponentRenderType.Title.ToString()); parent.InsertBefore(text, parent.FirstChild); }
internal ExcelChartTitle(XmlNamespaceManager nameSpaceManager, XmlNode node) : base(nameSpaceManager, node) { XmlNode topNode = node.SelectSingleNode("c:title", NameSpaceManager); if (topNode == null) { topNode = node.OwnerDocument.CreateElement("c", "title", ExcelPackage.schemaChart); node.InsertBefore(topNode, node.ChildNodes[0]); topNode.InnerXml = "<c:tx><c:rich><a:bodyPr /><a:lstStyle /><a:p><a:r><a:t /></a:r></a:p></c:rich></c:tx><c:layout />"; } TopNode = topNode; }
internal ExcelChartTitle(XmlNamespaceManager nameSpaceManager, XmlNode node) : base(nameSpaceManager, node) { XmlNode topNode = node.SelectSingleNode("c:title", NameSpaceManager); if (topNode == null) { topNode = node.OwnerDocument.CreateElement("c", "title", ExcelPackage.schemaChart); node.InsertBefore(topNode, node.ChildNodes[0]); topNode.InnerXml = "<c:tx><c:rich><a:bodyPr /><a:lstStyle /><a:p><a:pPr><a:defRPr sz=\"1800\" b=\"0\" /></a:pPr><a:r><a:t /></a:r></a:p></c:rich></c:tx><c:layout /><c:overlay val=\"0\" />"; } TopNode = topNode; SchemaNodeOrder = new string[] { "tx","bodyPr", "lstStyle", "layout", "overlay" }; }
/// <summary> /// Sorts a XmlNodeList alphbeticlly, by the names of the elements. /// Uses bubble sort. /// </summary> /// <param name="a_toSort">The node list to sort.</param> public static void SortElements(XmlNode a_toSort) { bool l_change = true; while (l_change) { l_change = false; for (int i=1; i<a_toSort.ChildNodes.Count; i++) { if ( String.Compare(a_toSort.ChildNodes[i].Name, a_toSort.ChildNodes[i-1].Name, true) < 0) { //Replace: a_toSort.InsertBefore(a_toSort.ChildNodes[i], a_toSort.ChildNodes[i-1]); l_change = true; } } } }
private void UpdateXmlNode(XmlNode node, string collectionName, string itemName, string lcid, string description) { XmlNode refNode; if (collectionName == "Titles" && node.FirstChild != null) { //Title should allways be first elemnt refNode = node.FirstChild; } else { switch (node.Name) { case "Area": refNode = node.SelectSingleNode("Group"); break; case "Group": refNode = node.SelectSingleNode("SubArea"); break; case "SubArea": refNode = node.SelectSingleNode("Privilege"); break; default: throw new Exception("Unexpected node name"); } } var labelsNode = node.SelectSingleNode(collectionName); if (labelsNode == null) { labelsNode = node.OwnerDocument.CreateElement(collectionName); if (refNode != null) { node.InsertBefore(labelsNode, refNode); } else { node.AppendChild(labelsNode); } } var labelNode = labelsNode.SelectSingleNode(string.Format(itemName + "[@LCID='{0}']", lcid)); if (labelNode == null) { labelNode = node.OwnerDocument.CreateElement(itemName); labelsNode.AppendChild(labelNode); var languageAttr = node.OwnerDocument.CreateAttribute("LCID"); languageAttr.Value = lcid; labelNode.Attributes.Append(languageAttr); var descriptionAttr = node.OwnerDocument.CreateAttribute(itemName); labelNode.Attributes.Append(descriptionAttr); } labelNode.Attributes[itemName].Value = description; }
// 插入新对象到儿子们的最前面 public static XmlNode InsertFirstChild(XmlNode parent, XmlNode newChild) { XmlNode refChild = null; if (parent.ChildNodes.Count > 0) refChild = parent.ChildNodes[0]; return parent.InsertBefore(newChild, refChild); }
// From http://stackoverflow.com/questions/475293/change-the-node-names-in-an-xml-file-using-c-sharp . static XmlElement RenameElement(XmlNode parent, XmlNode child, string newName) { // get existing 'Content' node // XmlNode contentNode = parent.SelectSingleNode("Content"); // create new (renamed) Content node XmlElement newNode = parent.OwnerDocument.CreateElement(newName); // [if needed] copy existing Content children newNode.InnerXml = child.InnerXml; foreach(XmlAttribute attr in child.Attributes) newNode.SetAttribute(attr.Name, attr.Value); // replace existing Content node with newly renamed Content node parent.InsertBefore(newNode, child); parent.RemoveChild(child); return newNode; }
/// <summary> /// Flex had been writing some 'text' elements in lift/lift-ranges files using the RelaxNg gramamr spec, but as a literal, /// not what the grammar was saying. This method fixes those, if needed. /// /// There is not really good place to do that, so here is where it happens. /// </summary> private static XmlNode PossiblyRenameElementHack(XmlNode parent, XmlNode childNodeAsVariable) { if (childNodeAsVariable.NodeType != XmlNodeType.Element) return childNodeAsVariable; // Do nothing at all, if it isn't <element>. if (childNodeAsVariable.Name != "element") return childNodeAsVariable; var doc = childNodeAsVariable.OwnerDocument; var docRoot = doc.DocumentElement; if (docRoot.Name != "lift" && docRoot.Name != "lift-ranges") return childNodeAsVariable; // Skip data that isn't lift or lift-range var newElement = doc.CreateElement("text"); while (childNodeAsVariable.HasChildNodes) { newElement.AppendChild(childNodeAsVariable.FirstChild); } // Removes bogus 'text' attribute, by ignoring it. parent.InsertBefore(newElement, childNodeAsVariable); parent.RemoveChild(childNodeAsVariable); childNodeAsVariable = newElement; return childNodeAsVariable; }
// //createListElement // private static void createListElement( ref System.Xml.XmlDocument pdoc, string pname, string pcore, System.Collections.Generic.List <pvMetadata.ListtemplateContenttype> ptypestable, System.Collections.Generic.List <pvMetadata.ListtemplateColumn> pfieldstable) { // // Insert ContentTypeRef // System.Xml.XmlNode contenttypes = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes", s_nsMgr); foreach (ListtemplateContenttype typ in ptypestable) { string ContentTypeID; switch (typ.BasedOn) { case "Element": ContentTypeID = "0x01" + "00" + typ.typeGUID; break; case "Annoncering": ContentTypeID = "0x0104" + "00" + typ.typeGUID; break; case "Hyperlink": ContentTypeID = "0x0105" + "00" + typ.typeGUID; break; case "'Kontaktperson": ContentTypeID = "0x0106" + "00" + typ.typeGUID; break; case "'Meddelelse": ContentTypeID = "0x0107" + "00" + typ.typeGUID; break; case "'Opgave": ContentTypeID = "0x0108" + "00" + typ.typeGUID; break; case "'Problem": ContentTypeID = "0x0103" + "00" + typ.typeGUID; break; default: ContentTypeID = "Error" + "00" + typ.typeGUID; break; } System.Xml.XmlElement contenttyperef = pdoc.CreateElement("", "ContentTypeRef", s_ns); System.Xml.XmlComment contenttypescomment = pdoc.CreateComment(typ.SysName); contenttyperef.SetAttribute("ID", ContentTypeID); System.Xml.XmlNode ContentTypeRef0x01 = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]", s_nsMgr); if (ContentTypeRef0x01 == null) { System.Xml.XmlNode lastContentTypeRef = contenttypes.AppendChild(contenttyperef); contenttypes.InsertBefore(contenttypescomment, lastContentTypeRef); } else { System.Xml.XmlNode Folder = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]/mha:Folder", s_nsMgr); if (Folder != null) { System.Xml.XmlNode copyFolder = Folder.CloneNode(true); contenttyperef.AppendChild(copyFolder); } contenttypes.InsertBefore(contenttypescomment, ContentTypeRef0x01); contenttypes.ReplaceChild(contenttyperef, ContentTypeRef0x01); } } System.Collections.Generic.SortedDictionary <string, ListtemplateColumn> scol = new System.Collections.Generic.SortedDictionary <string, ListtemplateColumn>(); foreach (ListtemplateColumn col in pfieldstable) { scol.Add(col.Seqnr, col); } // // Insert Field in Fields // System.Xml.XmlNode fields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Fields", s_nsMgr); foreach (ListtemplateColumn col in scol.Values) { if (!col.SysCol) { System.Xml.XmlElement fieldref = pdoc.CreateElement("", "Field", s_ns); fieldref.SetAttribute("Name", col.SysName); fieldref.SetAttribute("ID", col.colGUID); fieldref.SetAttribute("DisplayName", "$Resources:" + pcore + "," + col.SysName + ";"); switch (col.KolonneType) { case "Text": fieldref.SetAttribute("Type", "Text"); break; case "Note": fieldref.SetAttribute("Type", "Note"); fieldref.SetAttribute("NumLines", "3"); fieldref.SetAttribute("RichText", "TRUE"); break; case "Choice": fieldref.SetAttribute("Type", "Choice"); break; case "Number": fieldref.SetAttribute("Type", "Number"); fieldref.SetAttribute("Decimals", "0"); break; case "Percentage": fieldref.SetAttribute("Type", "Number"); fieldref.SetAttribute("Percentage", "TRUE"); fieldref.SetAttribute("Min", "0"); fieldref.SetAttribute("Max", "1"); break; case "Currency": fieldref.SetAttribute("Type", "Currency"); fieldref.SetAttribute("Decimals", "2"); break; case "DateOnly": fieldref.SetAttribute("Type", "DateTime"); fieldref.SetAttribute("Format", "DateOnly"); break; case "DateTime": fieldref.SetAttribute("Type", "DateTime"); break; case "Boolean": fieldref.SetAttribute("Type", "Boolean"); break; case "Counter": fieldref.SetAttribute("Type", "Counter"); break; case "Picture": fieldref.SetAttribute("Type", "Picture"); break; case "Hyperlink": fieldref.SetAttribute("Type", "Hyperlink"); break; default: break; } fields.AppendChild(fieldref); } } // // Insert FieldsRef in ViewFields // System.Xml.XmlNode viewfields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Views/mha:View[@BaseViewID=\"1\"]/mha:ViewFields", s_nsMgr); foreach (ListtemplateColumn col in scol.Values) { if (!col.SysCol) { System.Xml.XmlElement fieldref = pdoc.CreateElement("", "FieldRef", s_ns); fieldref.SetAttribute("ID", col.colGUID); fieldref.SetAttribute("Name", col.SysName); viewfields.AppendChild(fieldref); } } }
/// <summary>Convert from old soil XML format to new soil XML format</summary> /// <param name="Node">The node to convert</param> private static void ToVersion20(XmlNode Node) { if (Node.Name.ToLower() == "soil") { // If there is a <Phosphorus> node then get rid of it. It is old and not used. XmlNode OldPhosphorusNode = XmlUtilities.FindByType(Node, "Phosphorus"); if (OldPhosphorusNode != null) Node.RemoveChild(OldPhosphorusNode); XmlNode ProfileNode = XmlUtilities.Find(Node, "profile"); if (ProfileNode != null) { XmlNode WaterNode = Node.AppendChild(Node.OwnerDocument.CreateElement("Water")); XmlNode SoilWatNode = Node.AppendChild(Node.OwnerDocument.CreateElement("SoilWat")); XmlNode SOMNode = Node.AppendChild(Node.OwnerDocument.CreateElement("SoilOrganicMatter")); XmlNode LABNode = Node.AppendChild(Node.OwnerDocument.CreateElement("Lab")); XmlNode CountryNode = AnnotateNode(Node, "Country", "", ""); Node.InsertBefore(CountryNode, Node.FirstChild); AnnotateNode(Node, "State", "", ""); AnnotateNode(Node, "Region", "", ""); AnnotateNode(Node, "NearestTown", "", "Nearest town"); AnnotateNode(Node, "Site", "", ""); AnnotateNode(Node, "ApsoilNumber", "", "Apsoil number"); AnnotateNode(Node, "SoilType", "", "Classification"); AnnotateNode(Node, "Latitude", "", "Latitude (WGS84)"); AnnotateNode(Node, "Langitude", "", "Longitude (WGS84)"); AnnotateNode(Node, "LocationAccuracy", "", "Location accuracy"); AnnotateNode(Node, "NaturalVegetation", "", "Natural vegetation"); AnnotateNode(Node, "DataSource", "multiedit", "Data source"); AnnotateNode(Node, "Comment", "multiedit", "Comments"); XmlNode ConaNode = XmlUtilities.Find(Node, "CONA"); if (ConaNode != null) { XmlUtilities.SetValue(SoilWatNode, "SummerCona", ConaNode.InnerText); XmlUtilities.SetValue(SoilWatNode, "WinterCona", ConaNode.InnerText); Node.RemoveChild(ConaNode); XmlNode UNode = XmlUtilities.Find(Node, "U"); if (UNode != null) { XmlUtilities.SetValue(SoilWatNode, "SummerU", UNode.InnerText); XmlUtilities.SetValue(SoilWatNode, "WinterU", UNode.InnerText); Node.RemoveChild(UNode); } } else { MoveSoilNode(Node, "SummerCona", SoilWatNode); MoveSoilNode(Node, "SummerU", SoilWatNode); MoveSoilNode(Node, "SummerDate", SoilWatNode); MoveSoilNode(Node, "WinterCona", SoilWatNode); MoveSoilNode(Node, "WinterU", SoilWatNode); MoveSoilNode(Node, "WinterDate", SoilWatNode); } if (XmlUtilities.Value(SoilWatNode, "SummerDate") == "") XmlUtilities.SetValue(SoilWatNode, "SummerDate", "1-Nov"); if (XmlUtilities.Value(SoilWatNode, "WinterDate") == "") XmlUtilities.SetValue(SoilWatNode, "WinterDate", "1-Apr"); MoveSoilNode(Node, "DiffusConst", SoilWatNode); MoveSoilNode(Node, "DiffusSlope", SoilWatNode); MoveSoilNode(Node, "SALB", SoilWatNode); MoveSoilNode(Node, "CN2Bare", SoilWatNode); MoveSoilNode(Node, "CNRed", SoilWatNode); MoveSoilNode(Node, "CNCov", SoilWatNode); MoveSoilNode(Node, "CNCanopyFact", SoilWatNode); MoveSoilNode(Node, "DiffusConst", SoilWatNode); MoveSoilNode(Node, "RootCN", SoilWatNode); MoveSoilNode(Node, "RootWT", SoilWatNode); MoveSoilNode(Node, "SoilCN", SoilWatNode); MoveSoilNode(Node, "EnrACoeff", SoilWatNode); MoveSoilNode(Node, "EnrBCoeff", SoilWatNode); foreach (XmlNode LayerNode in XmlUtilities.ChildNodes(ProfileNode, "Layer")) { XmlNode WaterLayerNode = WaterNode.AppendChild(Node.OwnerDocument.CreateElement("Layer")); XmlNode SoilWatLayerNode = SoilWatNode.AppendChild(Node.OwnerDocument.CreateElement("Layer")); XmlNode SOMLayerNode = SOMNode.AppendChild(Node.OwnerDocument.CreateElement("Layer")); XmlNode LABLayerNode = LABNode.AppendChild(Node.OwnerDocument.CreateElement("Layer")); SetValue(WaterLayerNode, "Thickness", XmlUtilities.Value(LayerNode, "Thickness"), "mm"); SetValue(SoilWatLayerNode, "Thickness", XmlUtilities.Value(LayerNode, "Thickness"), "mm"); SetValue(SOMLayerNode, "Thickness", XmlUtilities.Value(LayerNode, "Thickness"), "mm"); SetValue(LABLayerNode, "Thickness", XmlUtilities.Value(LayerNode, "Thickness"), "mm"); SetValue(WaterLayerNode, "BD", XmlUtilities.Value(LayerNode, "BD"), "g/cc"); SetValue(WaterLayerNode, "AirDry", XmlUtilities.Value(LayerNode, "AirDry"), "mm/mm"); SetValue(WaterLayerNode, "LL15", XmlUtilities.Value(LayerNode, "LL15"), "mm/mm"); SetValue(WaterLayerNode, "DUL", XmlUtilities.Value(LayerNode, "DUL"), "mm/mm"); SetValue(WaterLayerNode, "SAT", XmlUtilities.Value(LayerNode, "SAT"), "mm/mm"); SetValue(WaterLayerNode, "KS", XmlUtilities.Value(LayerNode, "KS"), "mm/day"); foreach (XmlNode LLNode in XmlUtilities.ChildNodes(LayerNode, "ll")) { string CropName = XmlUtilities.NameAttr(LLNode); XmlNode CropNode = XmlUtilities.Find(WaterNode, CropName); if (CropNode == null) { CropNode = WaterNode.AppendChild(Node.OwnerDocument.CreateElement("SoilCrop")); XmlUtilities.SetNameAttr(CropNode, CropName); } XmlNode CropLayerNode = CropNode.AppendChild(Node.OwnerDocument.CreateElement("Layer")); SetValue(CropLayerNode, "Thickness", XmlUtilities.Value(LayerNode, "Thickness"), "mm"); SetValue(CropLayerNode, "LL", LLNode.InnerText, "mm/mm"); if (XmlUtilities.ChildByNameAndType(LayerNode, CropName, "KL") != null) SetValue(CropLayerNode, "KL", XmlUtilities.ChildByNameAndType(LayerNode, CropName, "KL").InnerText, "/day"); if (XmlUtilities.ChildByNameAndType(LayerNode, CropName, "XF") != null) SetValue(CropLayerNode, "XF", XmlUtilities.ChildByNameAndType(LayerNode, CropName, "XF").InnerText, "0-1"); } SetValue(SoilWatLayerNode, "SWCON", XmlUtilities.Value(LayerNode, "SWCON"), "0-1"); SetValue(SoilWatLayerNode, "MWCON", XmlUtilities.Value(LayerNode, "MWCON"), "0-1"); SetValue(SOMLayerNode, "OC", XmlUtilities.Value(LayerNode, "OC"), "Total %"); SetValue(SOMLayerNode, "FBiom", XmlUtilities.Value(LayerNode, "FBiom"), "0-1"); SetValue(SOMLayerNode, "FInert", XmlUtilities.Value(LayerNode, "FInert"), "0-1"); SetValue(LABLayerNode, "Rocks", XmlUtilities.Value(LayerNode, "Rocks"), "%"); SetValue(LABLayerNode, "Texture", XmlUtilities.Value(LayerNode, "Texture"), ""); SetValue(LABLayerNode, "EC", XmlUtilities.Value(LayerNode, "EC"), "1:5 dS/m"); SetValue(LABLayerNode, "PH", XmlUtilities.Value(LayerNode, "PH"), "1:5 water"); SetValue(LABLayerNode, "CL", XmlUtilities.Value(LayerNode, "CL"), "mg/kg"); SetValue(LABLayerNode, "Boron", XmlUtilities.Value(LayerNode, "Boron"), "mg/kg"); SetValue(LABLayerNode, "CEC", XmlUtilities.Value(LayerNode, "CEC"), "cmol+/kg"); SetValue(LABLayerNode, "Ca", XmlUtilities.Value(LayerNode, "Ca"), "cmol+/kg"); SetValue(LABLayerNode, "Mg", XmlUtilities.Value(LayerNode, "Mg"), "cmol+/kg"); SetValue(LABLayerNode, "Na", XmlUtilities.Value(LayerNode, "Na"), "cmol+/kg"); SetValue(LABLayerNode, "K", XmlUtilities.Value(LayerNode, "K"), "cmol+/kg"); SetValue(LABLayerNode, "ESP", XmlUtilities.Value(LayerNode, "ESP"), "%"); SetValue(LABLayerNode, "Mn", XmlUtilities.Value(LayerNode, "Mn"), "mg/kg"); SetValue(LABLayerNode, "Al", XmlUtilities.Value(LayerNode, "Al"), "meq/100g"); SetValue(LABLayerNode, "ParticleSizeSand", XmlUtilities.Value(LayerNode, "ParticleSizeSand"), "%"); SetValue(LABLayerNode, "ParticleSizeSilt", XmlUtilities.Value(LayerNode, "ParticleSizeSilt"), "%"); SetValue(LABLayerNode, "ParticleSizeClay", XmlUtilities.Value(LayerNode, "ParticleSizeClay"), "%"); } // Move phosphorus stuff if necessary. if (XmlUtilities.Value(Node, "RootCP") != "" && ProfileNode != null) { XmlNode PhosphorusNode = Node.AppendChild(Node.OwnerDocument.CreateElement("Phosphorus")); MoveSoilNode(Node, "RootCP", PhosphorusNode); MoveSoilNode(Node, "RateDissolRock", PhosphorusNode); MoveSoilNode(Node, "RateLossAvail", PhosphorusNode); foreach (XmlNode LayerNode in ProfileNode) { XmlNode PhosphorusLayerNode = PhosphorusNode.AppendChild(Node.OwnerDocument.CreateElement("Layer")); SetValue(PhosphorusLayerNode, "Thickness", XmlUtilities.Value(LayerNode, "Thickness"), "mm"); SetValue(PhosphorusLayerNode, "LabileP", XmlUtilities.Value(LayerNode, "LabileP"), "mg/kg"); SetValue(PhosphorusLayerNode, "BandedP", XmlUtilities.Value(LayerNode, "BandedP"), "kg/ha"); SetValue(PhosphorusLayerNode, "RockP", XmlUtilities.Value(LayerNode, "RockP"), "kg/ha"); SetValue(PhosphorusLayerNode, "Sorption", XmlUtilities.Value(LayerNode, "Sorption"), "-"); } } Node.RemoveChild(ProfileNode); } // Turn the <InitNitrogen> element into a sample node. XmlNode InitNitrogenNode = XmlUtilities.Find(Node, "InitNitrogen"); if (InitNitrogenNode != null) ConvertSampleNode(Node, InitNitrogenNode, "Initial nitrogen"); // Turn the <InitWater> element into a sample node IF it has layered values. XmlNode InitWaterNode = XmlUtilities.Find(Node, "InitWater"); if (InitWaterNode != null) ConvertSampleNode(Node, InitWaterNode, "Initial water"); // Change all <SoilSample> nodes to <Sample> foreach (XmlNode Child in XmlUtilities.ChildNodes(Node, "SoilSample")) ConvertSampleNode(Node, Child, XmlUtilities.NameAttr(Child)); // Change any soil p nodes. foreach (XmlNode child in XmlUtilities.ChildNodes(Node, "soilp")) Node.ParentNode.RemoveChild(child); } }
private void removeLinkto(XmlNode node) { if (node.NodeType == XmlNodeType.Element) { if (node.HasChildNodes) foreach (XmlNode child in node.ChildNodes) removeLinkto(child); Collection<string> attrsToBeRemoved = new Collection<string>(); //look for linkto attributes and attributes with @linkto value foreach (XmlAttribute xattr in node.Attributes) { if (xattr.Name.Equals("linkto"))//linkto attribute { XmlNode linktoNode = node.Attributes.GetNamedItem("linkto"); if (linktoNode != null) { string linksto = linktoNode.Value; //node.Attributes.RemoveNamedItem("linkto");//cannot change foreach collection attrsToBeRemoved.Add(xattr.Name); XmlNode valueofNode = node.OwnerDocument.CreateElement("xsl", "value-of", "http://www.w3.org/1999/XSL/Transform"); XmlAttribute selectattr = node.OwnerDocument.CreateAttribute("select"); selectattr.Value = linksto; valueofNode.Attributes.Append(selectattr); XmlNode innerTextNode = node.SelectSingleNode("text()"); if (innerTextNode != null) innerTextNode.InnerText = string.Empty; node.AppendChild(valueofNode); //generate tooltip -> would not work with SVG /*XmlAttribute tooltipAttr = node.OwnerDocument.CreateAttribute("ToolTip"); tooltipAttr.Value = linksto; if (node.Name.IndexOf('.') == -1) { node.Attributes.Append(tooltipAttr); } else if ((node.ParentNode != null) && (node.ParentNode.Name.IndexOf('.') == -1)) { node.ParentNode.Attributes.Append(tooltipAttr); }*/ } } else if (xattr.Value.StartsWith("@linkto")) { //linkto generates an attribute attrsToBeRemoved.Add(xattr.Name); string linkstoAttributeName = xattr.Name; string linksto = xattr.Value.Substring(xattr.Value.IndexOf("=") + 1); //remove @linkto=, sample format is Fill="@linkto=Color|Green" string linkstoAttributeValue; string linkstoAttributeDefault; if (linksto.Contains("|"))//"Color|Green" { linkstoAttributeDefault = linksto.Substring(linksto.IndexOf("|") + 1); linkstoAttributeValue = linksto.Substring(0, linksto.IndexOf("|")); } else//"Color" { linkstoAttributeValue = linksto; linkstoAttributeDefault = ""; } //generate XSL code for the attribute XmlNode attributeNode = node.OwnerDocument.CreateElement("xsl", "attribute", "http://www.w3.org/1999/XSL/Transform"); XmlAttribute attrName = node.OwnerDocument.CreateAttribute("name"); attrName.Value = linkstoAttributeName; attributeNode.Attributes.Append(attrName); XmlNode valueofNode = node.OwnerDocument.CreateElement("xsl", "value-of", "http://www.w3.org/1999/XSL/Transform"); XmlAttribute selectattr = node.OwnerDocument.CreateAttribute("select"); selectattr.Value = linkstoAttributeValue; valueofNode.Attributes.Append(selectattr); attributeNode.AppendChild(valueofNode); node.InsertBefore(attributeNode, node.FirstChild);//XSL to append attribute to the parent node //MessageBox.Show("Name: " + linkstoAttributeName + "\nValue: " + linkstoAttributeValue+ "\nDefault: "+linkstoAttributeDefault); } } //remove previous attributes foreach (string sattr in attrsToBeRemoved) { node.Attributes.RemoveNamedItem(sattr); } //clear collection attrsToBeRemoved.Clear(); } }
public XmlNode VerifyRefrence(Session session,State state, XmlNode xmlCommands, out bool changed) { changed = false; if (!(state is TraderState)) return xmlCommands; TraderState tradingConsoleState = (TraderState)state; List<Guid> instrumentIDs = new List<Guid>(); try { foreach (XmlElement xmlElement in xmlCommands.ChildNodes) { XmlElement tran = null; Guid instrumentID = Guid.Empty; switch (xmlElement.Name) { case "Execute2": tran = (XmlElement)xmlElement.GetElementsByTagName("Transaction")[0]; instrumentID = XmlConvert.ToGuid(tran.Attributes["InstrumentID"].Value); if (!tradingConsoleState.InstrumentsView.ContainsKey(instrumentID)) { instrumentIDs.Add(instrumentID); changed = true; } break; case "Place": tran = (XmlElement)xmlElement.GetElementsByTagName("Transaction")[0]; instrumentID = XmlConvert.ToGuid(tran.Attributes["InstrumentID"].Value); if (!tradingConsoleState.Instruments.ContainsKey(instrumentID)) { instrumentIDs.Add(instrumentID); changed = true; } break; } } if (instrumentIDs.Count > 0) { DataSet dataSet = this.GetInstruments(session,instrumentIDs); XmlDocument xmlDocument = xmlCommands.OwnerDocument; XmlElement parameters = xmlDocument.CreateElement("Parameters"); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); System.IO.StringWriter instrumentWriter = new System.IO.StringWriter(stringBuilder); System.Xml.XmlWriter instrumentXmlWriter = new XmlTextWriter(instrumentWriter); System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(DataSet)); xmlSerializer.Serialize(instrumentXmlWriter, dataSet); parameters.SetAttribute("DataSet", stringBuilder.ToString()); xmlCommands.InsertBefore(parameters, xmlCommands.FirstChild); changed = true; } } catch (System.Exception ex) { _Logger.Error(ex); } return xmlCommands; }
public static void insertSequence(XmlElement element, XmlNode root) { string strTag = GetTag(element); if (strTag == "###") { // TODO: 注意插入前是否已经有了一个头标区,避免插入后变成两个 root.InsertBefore(root.OwnerDocument.ImportNode(element, true), null); return; } // 寻找插入位置 List<int> values = new List<int>(); // 累积每个比较结果数字 int nInsertPos = -1; int i = 0; foreach (XmlNode current in root.ChildNodes) { if (current.NodeType != XmlNodeType.Element) { i++; continue; } XmlElement current_element = (XmlElement)current; string strCurrentTag = GetTag(current_element); int nBigThanCurrent = 0; // 相当于node和当前对象相减 nBigThanCurrent = string.Compare(strTag, strCurrentTag); if (nBigThanCurrent < 0) { nInsertPos = i; break; } if (nBigThanCurrent == 0) { /* if ((style & InsertSequenceStyle.PreferHead) != 0) { nInsertPos = i; break; } * */ } // 刚刚遇到过相等的一段,但在当前位置结束了相等 (或者开始变大,或者开始变小) if (nBigThanCurrent != 0 && values.Count > 0 && values[values.Count - 1] == 0) { nInsertPos = i - 1; break; } values.Add(nBigThanCurrent); i++; } if (nInsertPos == -1) { root.AppendChild(root.OwnerDocument.ImportNode(element, true)); return; } root.InsertBefore(root.OwnerDocument.ImportNode(element, true), root.ChildNodes[nInsertPos]); }
private static void MergePropertyAndGroup(XmlNode newParent, XmlNode mergingParent, string name) { Dictionary<string, XmlNode> propertyDict = new Dictionary<string, XmlNode>(); Dictionary<string, XmlNode> groupDict = new Dictionary<string, XmlNode>(); string value = ""; //record the first property node where the Group node to insert before XmlNode firstProperty = null; foreach (XmlNode child in mergingParent.ChildNodes) { if (child.NodeType == XmlNodeType.Element) { value = child.Attributes[name].Value; try { if (child.Name == "Property") { propertyDict.Add(value, child); } else groupDict.Add(value, child); } catch { throw new InvalidOperationException("Duplicate node with type\"" + child.Name + "name \"" + name + "\"=\"" + value + "\" found."); } } } foreach (XmlNode child in groupDict.Values) { bool duplicate = false; XmlNode old = null; foreach (XmlNode xn in newParent.ChildNodes) { if (xn.NodeType != XmlNodeType.Element) continue; if (xn.Name == "Property" && firstProperty == null) { firstProperty = xn; continue; } if (xn.Name == "Group" && xn.Attributes[name].Value == child.Attributes[name].Value) { duplicate = true; old = xn; break; } } if (duplicate) { MergePropertyAndGroup(old, child.CloneNode(true), name); } else { if(firstProperty == null) newParent.AppendChild(child.CloneNode(true)); else newParent.InsertBefore(child.CloneNode(true), firstProperty); } } foreach (XmlNode child in propertyDict.Values) { bool duplicate = false; XmlNode old = null; foreach (XmlNode xn in newParent.ChildNodes) { if (xn.NodeType != XmlNodeType.Element || xn.Name != "Property") continue; if (xn.Attributes[name].Value == child.Attributes[name].Value) { duplicate = true; old = xn; break; } } if (duplicate) { newParent.ReplaceChild(child.CloneNode(true), old); } else { newParent.AppendChild(child.CloneNode(true)); } } groupDict.Clear(); propertyDict.Clear(); }
/* // 删除一个方案 // return: // 0 not found // 1 found and deleted // 2 canceld 因此project没有被删除 public int DeleteProject(string strProjectNamePath, bool bWarning, out XmlNode parentXmlNode) { string strCodeFileName; bool bDeleteCodeFile = true; parentXmlNode = null; XmlNode nodeThis = LocateProjectNode(strProjectNamePath); if (nodeThis == null) return 0; strCodeFileName = DomUtil.GetAttr(nodeThis, "codeFileName"); if (strCodeFileName != "") { // 看看源文件是否被多个project引用 ArrayList aFound = new ArrayList(); XmlNodeList nodes = dom.DocumentElement.SelectNodes("//project"); for(int i=0;i<nodes.Count;i++) { string strFilePath = DomUtil.GetAttr(nodes[i], "codeFileName"); if (String.Compare(strCodeFileName, strFilePath, true) == 0) { if (nodes[i] != nodeThis) aFound.Add(nodes[i]); } } if (aFound.Count > 0) { if (bWarning == true) { string strText = "系统发现,源代码文件 " + strCodeFileName + " 除了被您即将删除的方案 "+ strProjectNamePath +" 使用外,还被下列方案引用:\r\n---\r\n"; for(int i=0;i<aFound.Count;i++) { strText += GetNodePathName((XmlNode)aFound[i]) + "\r\n"; } strText += "---\r\n\r\n这意味着,如果删除这个源代码文件,上述方案将不能正常运行。\r\n\r\n请问,在删除方案" +strProjectNamePath+ "时,是否保留源代码文件 " + strCodeFileName + "?"; DialogResult msgResult = MessageBox.Show(//this, strText, "script", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (msgResult == DialogResult.Yes) bDeleteCodeFile = false; if (msgResult == DialogResult.Cancel) return 2; // cancel } else { bDeleteCodeFile = false; // 自动采用最保险的方式 } } } // 从Dom上删除节点 parentXmlNode = nodeThis.ParentNode; parentXmlNode.RemoveChild(nodeThis); if (bDeleteCodeFile == true && strCodeFileName != "") File.Delete(strCodeFileName); m_bChanged = true; return 1; } */ // 上下移动节点 // return: // 0 not found // 1 found and moved // 2 cant move public int MoveNode(string strNodeNamePath, bool bUp, out XmlNode parentXmlNode) { parentXmlNode = null; XmlNode nodeThis = LocateAnyNode(strNodeNamePath); if (nodeThis == null) return 0; XmlNode nodeInsert = null; if (bUp == true) { nodeInsert = nodeThis.PreviousSibling; if (nodeInsert == null) return 2; } else { nodeInsert = nodeThis.NextSibling; if (nodeInsert == null) return 2; } // 从Dom上删除节点 parentXmlNode = nodeThis.ParentNode; parentXmlNode.RemoveChild(nodeThis); // 插入到特定位置 if (bUp == true) { parentXmlNode.InsertBefore(nodeThis, nodeInsert); } else { parentXmlNode.InsertAfter(nodeThis, nodeInsert); } m_bChanged = true; return 1; }
/// <summary> /// Merges two XML subtrees. /// </summary> /// <param name="destination">The destination node.</param> /// <param name="source">The source node.</param> /// <param name="variables">Variables to be substituted in attribute values.</param> /// <param name="append"><B>True</B> to append <paramref name="source"/>'s children nodes to /// <paramref name="destination"/>'s children list, <B>false</B> to insert them as first children.</param> /// <returns><B>True</B> if successfully merged, <B>false</B> otherwise.</returns> private static bool XmlMerge(XmlNode destination, XmlNode source, Dictionary<string, string> variables, bool append/*, bool skipX86Extensions*/) { if (destination.NodeType != source.NodeType || destination.Name != source.Name) return false; // check attributes for equality bool equals = true; if (source.Attributes != null && destination.Attributes != null) { foreach (XmlAttribute src_attr in source.Attributes) { XmlAttribute dst_attr = destination.Attributes[src_attr.Name]; if (dst_attr == null || dst_attr.Value != src_attr.Value) { equals = false; break; } } } if (!equals) return false; // iterate over children foreach (XmlNode src_child in source.ChildNodes) { if (src_child is XmlElement) { /*if (skipX86Extensions) { var ass = src_child.Attributes["assembly"]; // skip assemblies with this key, because they are not compatible with x64 system if (ass != null && ass.Value.Contains("PublicKeyToken=4ef6ed87c53048a3")) { continue; } }*/ equals = false; foreach (XmlNode dst_child in destination.ChildNodes) { if (XmlMerge(dst_child, src_child, variables, append/*, skipX86Extensions*/)) { equals = true; break; } } if (!equals) { // we are adding the source subtree here if (append) destination.AppendChild(XmlAdopt(destination, src_child, variables)); else destination.InsertBefore(XmlAdopt(destination, src_child, variables), destination.FirstChild); } } } return true; }
// 创建<borrowHistory>节点的下级内容 int CreateBorrowHistoryNode(XmlNode nodeBorrowHistory, string strField989, out string strWarning, out string strError) { strError = ""; strWarning = ""; int nRet = 0; XmlNode nodePrev = null; // 插入参考节点 // 进行子字段组循环 for (int g = 0; ; g++) { string strGroup = ""; // 从字段中得到子字段组 // parameters: // strField 字段。其中包括字段名、必要的指示符,字段内容。也就是调用GetField()函数所得到的字段。 // nIndex 子字段组序号。从0开始计数。 // strGroup [out]得到的子字段组。其中包括若干子字段内容。 // return: // -1 出错 // 0 所指定的子字段组没有找到 // 1 找到。找到的子字段组返回在strGroup参数中 nRet = MarcUtil.GetGroup(strField989, g, out strGroup); if (nRet == -1) { strError = "从MARC记录字段中获得子字段组 " + Convert.ToString(g) + " 时出错"; return -1; } if (nRet == 0) break; string strSubfield = ""; string strNextSubfieldName = ""; string strBarcode = ""; // 从字段或子字段组中得到一个子字段 // parameters: // strText 字段内容,或者子字段组内容。 // textType 表示strText中包含的是字段内容还是组内容。若为ItemType.Field,表示strText参数中为字段;若为ItemType.Group,表示strText参数中为子字段组。 // strSubfieldName 子字段名,内容为1位字符。如果==null,表示任意子字段 // 形式为'a'这样的。 // nIndex 想要获得同名子字段中的第几个。从0开始计算。 // strSubfield [out]输出子字段。子字段名(1字符)、子字段内容。 // strNextSubfieldName [out]下一个子字段的名字,内容一个字符 // return: // -1 出错 // 0 所指定的子字段没有找到 // 1 找到。找到的子字段返回在strSubfield参数中 nRet = MarcUtil.GetSubfield(strGroup, ItemType.Group, "a", 0, out strSubfield, out strNextSubfieldName); if (strSubfield.Length >= 1) { strBarcode = strSubfield.Substring(1); } if (String.IsNullOrEmpty(strBarcode) == true) continue; strBarcode = strBarcode.ToUpper(); XmlNode nodeBorrow = nodeBorrowHistory.OwnerDocument.CreateElement("borrow"); // If refChild is a null reference (Nothing in Visual Basic), insert newChild at the end of the list of child nodes nodeBorrow = nodeBorrowHistory.InsertBefore(nodeBorrow, nodePrev); nodePrev = nodeBorrow; // 删除超过100个的子节点 if (nodeBorrowHistory.ChildNodes.Count > 100) { XmlNode temp = nodeBorrowHistory.ChildNodes[nodeBorrowHistory.ChildNodes.Count - 1]; nodeBorrowHistory.RemoveChild(temp); } DomUtil.SetAttr(nodeBorrow, "barcode", strBarcode); // borrowDate属性 string strBorrowDate = ""; nRet = MarcUtil.GetSubfield(strGroup, ItemType.Group, "t", 0, out strSubfield, out strNextSubfieldName); if (strSubfield.Length >= 1) { strBorrowDate = strSubfield.Substring(1); if (strBorrowDate.Length != 8) { strBorrowDate = ""; } } if (String.IsNullOrEmpty(strBorrowDate) == false) { string strTarget = ""; nRet = Date8toRfc1123(strBorrowDate, out strTarget, out strError); if (nRet == -1) { strBorrowDate = ""; } else { strBorrowDate = strTarget; } } if (String.IsNullOrEmpty(strBorrowDate) == false) { DomUtil.SetAttr(nodeBorrow, "borrowDate", strBorrowDate); } } /* // delete more than 100 if (nodeBorrowHistory.ChildNodes.Count > 100) { XmlNodeList nodes = nodeBorrowHistory.SelectNodes("borrow"); for (int i = 100; i < nodes.Count; i++) { nodeBorrowHistory.RemoveChild(nodes[i]); } }*/ return 0; }
/// <summary> /// This handles merging of the custom component configurations into the configuration file including /// dependencies. /// </summary> /// <param name="id">The ID of the component to merge</param> /// <param name="factory">The build component factory</param> /// <param name="rootNode">The root container node</param> /// <param name="configNode">The configuration node to merge</param> /// <param name="isConceptualConfig">True if this is a conceptual content configuration file or false if /// it is a reference build configuration file.</param> /// <param name="mergeStack">A stack used to check for circular build component dependencies. Pass null /// on the first non-recursive call.</param> private void MergeComponent(string id, BuildComponentFactory factory, XmlNode rootNode, XmlNode configNode, bool isConceptualConfig, Stack<string> mergeStack) { BuildComponentFactory dependencyFactory; ComponentPlacement position; XmlNodeList matchingNodes; XmlNode node; string replaceId; // Merge dependent component configurations first if(factory.Dependencies.Any()) { if(mergeStack == null) mergeStack = new Stack<string>(); foreach(string dependency in factory.Dependencies) { node = rootNode.SelectSingleNode("component[@id='" + dependency + "']"); // If it's already there or would create a circular dependency, ignore it if(node != null || mergeStack.Contains(dependency)) continue; // Add the dependency with a default configuration if(!buildComponents.TryGetValue(dependency, out dependencyFactory)) throw new BuilderException("BE0023", String.Format(CultureInfo.CurrentCulture, "The project contains a reference to a custom build component '{0}' that has a " + "dependency '{1}' that could not be found.", id, dependency)); node = rootNode.OwnerDocument.CreateDocumentFragment(); node.InnerXml = substitutionTags.TransformText(dependencyFactory.DefaultConfiguration); this.ReportProgress(" Merging '{0}' dependency for '{1}'", dependency, id); mergeStack.Push(dependency); this.MergeComponent(dependency, dependencyFactory, rootNode, node, isConceptualConfig, mergeStack); mergeStack.Pop(); } } position = (!isConceptualConfig) ? factory.ReferenceBuildPlacement : factory.ConceptualBuildPlacement; // Find all matching components by ID replaceId = position.Id; matchingNodes = rootNode.SelectNodes("component[@id='" + replaceId + "']"); // If replacing another component, search for that by ID and replace it if found if(position.Placement == PlacementAction.Replace) { if(matchingNodes.Count < position.AdjustedInstance) { this.ReportProgress(" Could not find configuration '{0}' (instance {1}) to replace with " + "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id); // If it's a dependency, that's a problem if(mergeStack.Count != 0) throw new BuilderException("BE0024", "Unable to add dependent configuration: " + id); return; } rootNode.ReplaceChild(configNode, matchingNodes[position.AdjustedInstance - 1]); this.ReportProgress(" Replaced configuration for '{0}' (instance {1}) with configuration " + "for '{2}'", replaceId, position.AdjustedInstance, id); // Adjust instance values on matching components foreach(var component in buildComponents.Values) if(!isConceptualConfig) { if(component.ReferenceBuildPlacement.Id == replaceId && component.ReferenceBuildPlacement.AdjustedInstance > position.AdjustedInstance) { component.ReferenceBuildPlacement.AdjustedInstance--; } } else if(component.ConceptualBuildPlacement.Id == replaceId && component.ConceptualBuildPlacement.AdjustedInstance > position.AdjustedInstance) { component.ConceptualBuildPlacement.AdjustedInstance--; } return; } // See if the configuration already exists. If so, replace it. // We'll assume it's already in the correct location. node = rootNode.SelectSingleNode("component[@id='" + id + "']"); if(node != null) { this.ReportProgress(" Replacing default configuration for '{0}' with the custom configuration", id); rootNode.ReplaceChild(configNode, node); return; } // Create the node and add it in the correct location switch(position.Placement) { case PlacementAction.Start: rootNode.InsertBefore(configNode, rootNode.ChildNodes[0]); this.ReportProgress(" Added configuration for '{0}' to the start of the configuration file", id); break; case PlacementAction.End: rootNode.InsertAfter(configNode, rootNode.ChildNodes[rootNode.ChildNodes.Count - 1]); this.ReportProgress(" Added configuration for '{0}' to the end of the configuration file", id); break; case PlacementAction.Before: if(matchingNodes.Count < position.AdjustedInstance) this.ReportProgress(" Could not find configuration '{0}' (instance {1}) to add " + "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id); else { rootNode.InsertBefore(configNode, matchingNodes[position.AdjustedInstance - 1]); this.ReportProgress(" Added configuration for '{0}' before '{1}' (instance {2})", id, replaceId, position.AdjustedInstance); } break; default: // After if(matchingNodes.Count < position.AdjustedInstance) this.ReportProgress(" Could not find configuration '{0}' (instance {1}) to add " + "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id); else { rootNode.InsertAfter(configNode, matchingNodes[position.AdjustedInstance - 1]); this.ReportProgress(" Added configuration for '{0}' after '{1}' (instance {2})", id, replaceId, position.AdjustedInstance); } break; } }
/// <summary> /// Add a node to the XML tree. /// </summary> /// <param name="xnParent">An XmlNode specifying the parent of the new node.</param> /// <param name="xnNextSibling">An XmlNode specifying the next sibling of the new node.</param> /// <param name="xn">An XmlNode specifying the new node.</param> private void AddNodeFromDialogToDom(XmlNode xnParent, ref XmlNode xnNextSibling, ref XmlNode xn) { if (xn.NodeType == XmlNodeType.Attribute) { xn = xnParent.Attributes.Append((XmlAttribute)xn); } else if (xn.NodeType == XmlNodeType.Text && xnNextSibling == null && xnParent.LastChild != null && xnParent.LastChild.NodeType == XmlNodeType.Text) { //we want to append a text node after a text node //change the value of the existing one xnParent.LastChild.InnerText = xnParent.LastChild.InnerText + xn.InnerText; //delete it (it will get added back later as part of adding it to the treeview) try { m_dicXnTn[xnParent.LastChild].Remove(); m_dicXnTn.Remove(xnParent.LastChild); } catch (KeyNotFoundException) { // Happens if we explicitly add a text node, having already added the element } //let it get added back xn = xnParent.LastChild; } else if (xn.NodeType == XmlNodeType.Text && xnNextSibling != null && xnNextSibling.NodeType == XmlNodeType.Text) { //we want to add a text node ahead of another text node //change the value of the existing one xnNextSibling.InnerText = xn.InnerText + xnNextSibling.InnerText; //delete it (it will get added back later as part of adding it to the treeview) m_dicXnTn[xnNextSibling].Remove(); m_dicXnTn.Remove(xnNextSibling); //let it get added back xn = xnNextSibling; xnNextSibling = xnNextSibling.NextSibling; } else if (xn.NodeType == XmlNodeType.Text && xnNextSibling != null && xnNextSibling.PreviousSibling != null && xnNextSibling.PreviousSibling.NodeType == XmlNodeType.Text) { //we want to add a text node after another text node //change the value of the existing one xnNextSibling.PreviousSibling.InnerText = xnNextSibling.PreviousSibling.InnerText + xn.InnerText; //delete it m_dicXnTn[xnNextSibling.PreviousSibling].Remove(); m_dicXnTn.Remove(xnNextSibling.PreviousSibling); //let it get added back xn = xnNextSibling.PreviousSibling; } else { xn = xnParent.InsertBefore(xn, xnNextSibling); } xn.OwnerDocument.Normalize(); }
public static void InsertSorted(XmlNode parent, XmlNode child, Comparison<XmlNode> comparer) { foreach(XmlNode node in parent.ChildNodes) { if (comparer(node, child) > 0) { parent.InsertBefore(child, node); return; } } parent.AppendChild(child); }
private static XmlNode InsertBefore(XmlNode parent, XmlNode newChild, XmlNode refChild) { Assert.NotNull(parent); Assert.NotNull(newChild); return parent.InsertBefore(newChild, refChild); }
private void StripLangTag(XmlNode docNode, XmlNode langNode) { List<XmlNode> innerNodeList = new List<XmlNode>(); foreach (XmlNode innerNode in langNode.ChildNodes) { innerNodeList.Add(innerNode); } langNode.RemoveAll(); foreach (XmlNode innerNode in innerNodeList) { docNode.InsertBefore(innerNode, langNode); } docNode.RemoveChild(langNode); }
private void FillSampleListXML(XmlNode TOCnode, XmlNode nodeParent) { // Add all child sample nodes XmlNode sampleNode = FindNodeByAttribute(samplesXMLDoc, "ParentNodeID", TOCnode.Attributes["ID"].Value); while(sampleNode != null) { if(sampleNode.Name == "SampleConfig") { // Add child item into the XML nodeParent.AppendChild(nodeParent.OwnerDocument.ImportNode(sampleNode, true)); } // Find next child node sampleNode = FindNextNodeByAttribute(sampleNode, samplesXMLDoc, "ParentNodeID",TOCnode.Attributes["ID"].Value); } XmlNode node = TOCnode.FirstChild; while(node != null) { if(node.Name == "TOCNode") { sampleNode = FindNodeByAttribute(samplesXMLDoc, "ParentNodeID",node.Attributes["ID"].Value); //headers XmlNode newTOCNode = null; if(node["TOCNode"] != null || sampleNode != null) { //*** Position TOC node in the parent node depending on its priority // Get node priority int priority = 20000; if(node.Attributes["Priority"] != null) { priority = int.Parse(node.Attributes["Priority"].Value); } // Check if node should be moved XmlNode moveBeforeNode = null; XmlNode currentNode = nodeParent.LastChild; while(currentNode != null) { if(currentNode.Name == "SampleConfig") { int currentPriority = 10000; if(currentNode.Attributes["Priority"] != null) { currentPriority = int.Parse(currentNode.Attributes["Priority"].Value); } if(priority < currentPriority) { moveBeforeNode = currentNode; } } currentNode = currentNode.PreviousSibling; } // Add child item into the XML if(moveBeforeNode == null) { newTOCNode = nodeParent.AppendChild(nodeParent.OwnerDocument.ImportNode(node, false)); } else { newTOCNode = nodeParent.InsertBefore(nodeParent.OwnerDocument.ImportNode(node, false), moveBeforeNode); } // Add Title attribute XmlAttribute newAttr = nodeParent.OwnerDocument.CreateAttribute("Title"); newAttr.Value = node["Title"].InnerText; newTOCNode.Attributes.Append(newAttr); // Fill child items FillSampleListXML(node, newTOCNode); } } node = node.NextSibling; } }
/// <summary> /// Fix the order of the properties of the specified parent xml node to that /// giveen in ChildNodeNames /// </summary> private static void SetPropertiesOrder(XmlNode ParentNode, string[] ChildNodeNames, string[] Units, bool CheckUnits) { for (int i = 0; i < ChildNodeNames.Length; i++) { XmlNode Child = XmlUtilities.Find(ParentNode, ChildNodeNames[i]); if (Child == null) { Child = ParentNode.OwnerDocument.CreateElement(ChildNodeNames[i]); if (Units != null && Units[i] != "") XmlUtilities.SetAttribute(Child, "units", Units[i]); } Child = ParentNode.InsertBefore(Child, ParentNode.ChildNodes[i]); if (CheckUnits && XmlUtilities.Attribute(Child, "units") == "") XmlUtilities.SetAttribute(Child, "units", Units[i]); } }
protected override void InsertNewXmlNode(XmlNode parentElement, XmlNode newElement) { if (newElement.Name == "Package") { if (parentElement.FirstChild != null) { parentElement.InsertBefore(newElement, parentElement.FirstChild); } else { parentElement.AppendChild(newElement); } } else { base.InsertNewXmlNode(parentElement, newElement); } }
private void ReplaceInitialChildText(XmlNode parent, string value) { XmlNode n = parent.FirstChild; // don't consider whitespace when replacing initial text while (n != null && n.NodeType == XmlNodeType.Whitespace) n = n.NextSibling; if (n != null) { if (n.NodeType == XmlNodeType.Text) n.Value = value; else n = parent.InsertBefore(CreateTextNode(value), n); RemoveInitialTextNodes(n.NextSibling); } else { parent.AppendChild(CreateTextNode(value)); } }
/// <summary> /// Copy elements from source to overlay. Only elements that are missing in overlay are actually copied. /// The result of this operation is a new tree which looks like source with overlay's replacements pasted /// on top of it. This function is internal because the feature that uses it (copyOf) was cut for 1.0, and /// the function has not been heavily tested. Use at your own risk. /// </summary> /// <param name="source">The source tree.</param> /// <param name="overlay">The overlay tree. This tree will be modified in place.</param> /// <returns>The new tree</returns> internal static XmlNode _TreeOverlay(XmlNode source, XmlNode overlay) { foreach (XmlNode sourceChild in source.ChildNodes) { if (sourceChild.NodeType != XmlNodeType.Element) continue; // how many nodes with this name are in the source? XmlNodeList sourceNodes = source.SelectNodes(sourceChild.LocalName); // and how many in the overlay? XmlNodeList overlayNodes = overlay.SelectNodes(sourceChild.LocalName); // for the first n nodes common to both trees, we will just traverse // the subchildren. we don't copy nodes, because the overlay's data // takes precidence int numToTraverse = Math.Min(overlayNodes.Count, sourceNodes.Count); // for the remaining nodes that exist in source, but not overlay, copy // them over and traverse them int numToCopy = sourceNodes.Count - overlayNodes.Count; // traverse nodes first int i = 0; for (i = 0; i < numToTraverse; ++i) { _TreeOverlay(sourceNodes[i], overlayNodes[i]); } // now copy nodes int offset = i; for (i = 0; i < numToCopy; ++i) { XmlNode copy = sourceNodes[i + offset].CloneNode(true); _TreeOverlay(sourceNodes[i + offset], copy); overlay.AppendChild(copy); } } // reorder nodes in overlay to match source for (int i = 0; i < source.ChildNodes.Count; ++i) { XmlNode sourceNode = source.ChildNodes[i]; if (sourceNode.LocalName != overlay.ChildNodes[i].LocalName) { for (int j = i; j < overlay.ChildNodes.Count; ++j) { if (sourceNode.LocalName == overlay.ChildNodes[j].LocalName) { overlay.InsertBefore(overlay.ChildNodes[j], overlay.ChildNodes[i]); break; } } } } return overlay; }
private static void AddReferenceTo(XmlNode refItemGroup, Reference reference) { var doc = refItemGroup.OwnerDocument; var frag = doc.CreateDocumentFragment(); //can't seem to be able to remove the xmlns attribute so let's atleast set //it to the correct value //NOTE:formatting below is important! Try to recreate the exact same xml as VS to reduce the size of diffs if (reference.EmbeddedResource) { frag.InnerXml = String.Format(@" <Reference Include=""{0}""> <HintPath>{1}</HintPath> <Private>True</Private> </Reference>", reference.Include, reference.HintPath); } else { frag.InnerXml = String.Format(@" <Reference Include=""{0}""> <HintPath>{1}</HintPath> </Reference>", reference.Include, reference.HintPath); } refItemGroup.InsertBefore(frag, refItemGroup.FirstChild); }
/// <summary> /// 设置明细列,读取模板文件后设置 /// </summary> /// <param name="col">列</param> /// <param name="xmlRow">明细行</param> /// <param name="xmlTdNext">列单元格位置</param> private XmlNode setCol(DataColumn col, XmlNode xmlRow, XmlNode xmlTdNext,int ni) { XmlNode xmlCol = this.CtrlXmlSchema.Document.SelectSingleNode("//xs:sequence//xs:element[@name='" + col.ColumnName + "']", this._xmlNsMglSchema); if (this.CtrlWorkItem.ColumnKey == col.ColumnName || (null != xmlCol.Attributes["visible"] && "1" == xmlCol.Attributes["visible"].Value)) return null; string strDbType = xmlCol.Attributes["type"].Value; switch (strDbType.ToLower()) { case "xs:string": strDbType = "string"; break; case "xs:int": case "xs:integer": strDbType = "int"; break; case "xs:decimal": case "xs:double": case "xs:float": strDbType = "decimal"; break; case "xs:money": strDbType = "decimal"; break; case "xs:date": case "xs:datetime": strDbType = "date"; break; case "xs:boolean": strDbType = "bool"; break; default: strDbType = "string"; break; } //检查是否属于字典类型 if (null != xmlCol.Attributes["dataitem"] && null != xmlCol.Attributes["textcol"] && null != xmlCol.Attributes["valuecol"] && "" != xmlCol.Attributes["dataitem"].Value && "" != xmlCol.Attributes["textcol"].Value && "" != xmlCol.Attributes["valuecol"].Value) { string strDataItem = xmlCol.Attributes["dataitem"].Value; if (null != this.CtrlDsDict.Tables[strDataItem] && this.CtrlDsDict.Tables[strDataItem].Columns.Contains(xmlCol.Attributes["textcol"].Value) && this.CtrlDsDict.Tables[strDataItem].Columns.Contains(xmlCol.Attributes["valuecol"].Value)) strDbType = "select"; } string strDbTypeTmp = strDbType; if (null != xmlCol.Attributes["datastyle"] && "" != xmlCol.Attributes["datastyle"].Value) strDbType = xmlCol.Attributes["datastyle"].Value; XmlNode xmlTd = null; if (null != xmlCol.Attributes["isreadonly"] && ("true" == xmlCol.Attributes["isreadonly"].Value || "1" == xmlCol.Attributes["isreadonly"].Value)) { XmlNode xmlRowReadOnly = this._xmltpdoc.SelectSingleNode("//*[@rowType='readonly']"); xmlTd = xmlRowReadOnly.SelectSingleNode(".//*[@datatype='" + strDbType + "']"); if (null == xmlTd && strDbTypeTmp != strDbType) { strDbType = strDbTypeTmp; xmlTd = xmlRowReadOnly.SelectSingleNode(".//*[@datatype='" + strDbType + "']"); } if (null == xmlTd) { xmlTd = xmlRowReadOnly.SelectSingleNode(".//*[@datatype='string']"); strDbType = "string"; } } else { XmlNode xmlRowEdit = this._xmltpdoc.SelectSingleNode("//*[@rowType='edit']"); xmlTd = xmlRowEdit.SelectSingleNode(".//*[@datatype='" + strDbType + "']"); if (null == xmlTd && strDbTypeTmp != strDbType) { strDbType = strDbTypeTmp; xmlTd = xmlRowEdit.SelectSingleNode(".//*[@datatype='" + strDbType + "']"); } if (null == xmlTd) { xmlTd = xmlRowEdit.SelectSingleNode(".//*[@datatype='string']"); strDbType = "string"; } } if (null == xmlTd.Attributes["colname"]) xmlTd.Attributes.Append(xmlTd.OwnerDocument.CreateAttribute("colname")); if (null == xmlTd.Attributes["width"]) xmlTd.Attributes.Append(xmlTd.OwnerDocument.CreateAttribute("width")); else if (lastcol == col.ColumnName) xmlTd.Attributes["width"].Value = ""; else xmlTd.Attributes["width"].Value = swidth; //模板单元格作为列单元,//如果是字典列;处理绑定数据 XmlNode xmlTdNew = xmlRow.InsertBefore(xmlTd.Clone(), xmlTdNext); xmlTdNew.Attributes["colname"].Value = col.ColumnName; //字段列对格式的处理,增加格式列字段名属性 if (null == xmlTdNew.Attributes["format"] && null != xmlCol.Attributes["format"] && "" != xmlCol.Attributes["format"].Value) { xmlTdNew.Attributes.Append(xmlTdNew.OwnerDocument.CreateAttribute("format")); xmlTdNew.Attributes["format"].Value = xmlCol.Attributes["format"].Value; } if (null == xmlTdNew.Attributes["formatfld"] && null != xmlCol.Attributes["formatfld"] && "" != xmlCol.Attributes["formatfld"].Value) { xmlTdNew.Attributes.Append(xmlTdNew.OwnerDocument.CreateAttribute("formatfld")); xmlTdNew.Attributes["formatfld"].Value = xmlCol.Attributes["formatfld"].Value; } if (null != xmlCol.Attributes["width"] && "" != xmlCol.Attributes["width"].Value) xmlTdNew.Attributes["width"].Value = xmlCol.Attributes["width"].Value; //具有valuefld属性的控件,绑定指定的列字段:用于超链接类型,没有值就绑定字段自己 XmlNodeList xmlCtrlList = xmlTdNew.SelectNodes(".//*[@valuefld]"); for (int i = 0; i < xmlCtrlList.Count; i++) { XmlNode xmlNodeValue = xmlCtrlList[i]; if (null == xmlNodeValue.Attributes["datafld"]) xmlNodeValue.Attributes.Append(xmlNodeValue.OwnerDocument.CreateAttribute("datafld")); if (null == xmlCol.Attributes["valuefld"]) xmlNodeValue.Attributes["datafld"].Value = ""; else xmlNodeValue.Attributes["datafld"].Value = xmlCol.Attributes["valuefld"].Value; xmlNodeValue.Attributes["valuefld"].Value = xmlCtrlList[i].Attributes["datafld"].Value; //把当前列workitem定义的属性赋值给控件模板 for (int k = 0; k < xmlCol.Attributes.Count; k++) { string attname = xmlCol.Attributes[k].LocalName; if ("datafld" == attname || "valuefld" == attname) continue; if (null != xmlNodeValue.Attributes[xmlCol.Attributes[k].LocalName]) xmlNodeValue.Attributes[xmlCol.Attributes[k].LocalName].Value = xmlCol.Attributes[k].Value; } } xmlCtrlList = xmlTdNew.SelectNodes(".//*[@colname]"); for (int i = 0; i < xmlCtrlList.Count; i++) { if (null == xmlCtrlList[i].Attributes["datafld"]) xmlCtrlList[i].Attributes.Append(xmlCtrlList[i].OwnerDocument.CreateAttribute("datafld")); //有格式列字段,首先显示格式列字段,是select控件的直接绑定字段 if (null != xmlCol.Attributes["formatfld"] && "" != xmlCol.Attributes["formatfld"].Value) { xmlCtrlList[i].Attributes.Append(xmlCtrlList[i].OwnerDocument.CreateAttribute("formatfld")); xmlCtrlList[i].Attributes["formatfld"].Value = xmlCol.Attributes["formatfld"].Value; if ("select" != xmlCtrlList[i].LocalName.ToLower()) xmlCtrlList[i].Attributes["datafld"].Value = xmlCol.Attributes["formatfld"].Value; else xmlCtrlList[i].Attributes["datafld"].Value = col.ColumnName; } else xmlCtrlList[i].Attributes["datafld"].Value = col.ColumnName; xmlCtrlList[i].Attributes["colname"].Value = col.ColumnName; if (null != xmlCol.Attributes["maxlength"] && "" != xmlCol.Attributes["maxlength"].Value) { if (null == xmlCtrlList[i].Attributes["maxlength"]) xmlCtrlList[i].Attributes.Append(xmlCtrlList[i].OwnerDocument.CreateAttribute("maxlength")); xmlCtrlList[i].Attributes["maxlength"].Value = xmlCol.Attributes["maxlength"].Value; } //字典列数据,填充字典内容 if (("select" == strDbType || "selectbtn" == strDbType) && "select" == xmlCtrlList[i].LocalName.ToLower()) { if (null == xmlCtrlList[i].Attributes["DataSource"]) xmlCtrlList[i].Attributes.Append(xmlCtrlList[i].OwnerDocument.CreateAttribute("DataSource")); xmlCtrlList[i].Attributes["DataSource"].Value = xmlCol.Attributes["dataitem"].Value; if (null == xmlCtrlList[i].Attributes["DataTextField"]) xmlCtrlList[i].Attributes.Append(xmlCtrlList[i].OwnerDocument.CreateAttribute("DataTextField")); xmlCtrlList[i].Attributes["DataTextField"].Value = xmlCol.Attributes["textcol"].Value; if (null == xmlCtrlList[i].Attributes["DataValueField"]) xmlCtrlList[i].Attributes.Append(xmlCtrlList[i].OwnerDocument.CreateAttribute("DataValueField")); xmlCtrlList[i].Attributes["DataValueField"].Value = xmlCol.Attributes["valuecol"].Value; xmlCtrlList[i].AppendChild(xmlCtrlList[i].OwnerDocument.CreateElement("option")); for (int j = 0; j < this.CtrlDsDict.Tables[xmlCol.Attributes["dataitem"].Value].Rows.Count; j++) { DataRow dr = this.CtrlDsDict.Tables[xmlCol.Attributes["dataitem"].Value].Rows[j]; if (null == dr[xmlCol.Attributes["textcol"].Value] || DBNull.Value == dr[xmlCol.Attributes["textcol"].Value] || null == dr[xmlCol.Attributes["valuecol"].Value] || DBNull.Value == dr[xmlCol.Attributes["valuecol"].Value]) continue; XmlNode xmloption = xmlCtrlList[i].OwnerDocument.CreateElement("option"); XmlAttribute attrValue = xmlCtrlList[i].OwnerDocument.CreateAttribute("value"); attrValue.Value = dr[xmlCol.Attributes["valuecol"].Value].ToString(); xmloption.InnerXml = dr[xmlCol.Attributes["textcol"].Value].ToString(); xmloption.Attributes.Append(attrValue); xmlCtrlList[i].AppendChild(xmloption); } }//if("select"==strDbType && "select"==xmlCtrlList[i].LocalName.ToLower()) }//for(int i=0;i<xmlCtrlList.Count;i++) return xmlTdNew; }
/// <summary> /// This handles merging of the custom component configurations into /// the configuration file including dependencies. /// </summary> /// <param name="id">The ID of the component to merge</param> /// <param name="info">The build component definition</param> /// <param name="rootNode">The root container node</param> /// <param name="configNode">The configuration node to merge</param> /// <param name="isConceptualConfig">True if this is a conceptual /// content configuration file or false if it is a reference build /// configuration file.</param> private void MergeComponent(string id, BuildComponentInfo info, XmlNode rootNode, XmlNode configNode, bool isConceptualConfig) { BuildComponentInfo depInfo; ComponentPosition position; XmlNodeList matchingNodes; XmlNode node; string replaceId; // Merge dependent component configurations first if(info.Dependencies.Count != 0) foreach(string dependency in info.Dependencies) { node = rootNode.SelectSingleNode("component[@id='" + dependency + "']"); // If it's already there or would create a circular // dependency, ignore it. if(node != null || mergeStack.Contains(dependency)) continue; // Add the dependency with a default configuration if(!BuildComponentManager.BuildComponents.TryGetValue(dependency, out depInfo)) throw new BuilderException("BE0023", String.Format( CultureInfo.InvariantCulture, "The project contains " + "a reference to a custom build component '{0}' that " + "has a dependency '{1}' that could not be found.", id, dependency)); node = rootNode.OwnerDocument.CreateDocumentFragment(); node.InnerXml = reField.Replace(depInfo.DefaultConfiguration, fieldMatchEval); this.ReportProgress(" Merging '{0}' dependency for '{1}'", dependency, id); mergeStack.Push(dependency); this.MergeComponent(dependency, depInfo, rootNode, node, isConceptualConfig); mergeStack.Pop(); } position = (!isConceptualConfig) ? info.ReferenceBuildPosition : info.ConceptualBuildPosition; // Find all matching components by ID or type name if(!String.IsNullOrEmpty(position.Id)) { replaceId = position.Id; matchingNodes = rootNode.SelectNodes("component[@id='" + replaceId + "']"); } else { replaceId = position.TypeName; matchingNodes = rootNode.SelectNodes("component[@type='" + replaceId + "']"); } // If replacing another component, search for that by ID or // type and replace it if found. if(position.Place == ComponentPosition.Placement.Replace) { if(matchingNodes.Count < position.AdjustedInstance) { this.ReportProgress(" Could not find configuration '{0}' (instance {1}) to replace with " + "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id); // If it's a dependency, that's a problem if(mergeStack.Count != 0) throw new BuilderException("BE0024", "Unable to add dependent configuration: " + id); return; } rootNode.ReplaceChild(configNode, matchingNodes[position.AdjustedInstance - 1]); this.ReportProgress(" Replaced configuration for '{0}' (instance {1}) with configuration " + "for '{2}'", replaceId, position.AdjustedInstance, id); // Adjust instance values on matching components foreach(BuildComponentInfo component in BuildComponentManager.BuildComponents.Values) if(!isConceptualConfig) { if(((!String.IsNullOrEmpty(component.ReferenceBuildPosition.Id) && component.ReferenceBuildPosition.Id == replaceId) || (String.IsNullOrEmpty(component.ReferenceBuildPosition.Id) && component.ReferenceBuildPosition.TypeName == replaceId)) && component.ReferenceBuildPosition.AdjustedInstance > position.AdjustedInstance) component.ReferenceBuildPosition.AdjustedInstance--; } else if(((!String.IsNullOrEmpty(component.ConceptualBuildPosition.Id) && component.ConceptualBuildPosition.Id == replaceId) || (String.IsNullOrEmpty(component.ConceptualBuildPosition.Id) && component.ConceptualBuildPosition.TypeName == replaceId)) && component.ConceptualBuildPosition.AdjustedInstance > position.AdjustedInstance) component.ConceptualBuildPosition.AdjustedInstance--; return; } // See if the configuration already exists. If so, replace it. // We'll assume it's already in the correct location. node = rootNode.SelectSingleNode("component[@id='" + id + "']"); if(node != null) { this.ReportProgress(" Replacing default configuration for '{0}' with the custom configuration", id); rootNode.ReplaceChild(configNode, node); return; } // Create the node and add it in the correct location switch(position.Place) { case ComponentPosition.Placement.Start: rootNode.InsertBefore(configNode, rootNode.ChildNodes[0]); this.ReportProgress(" Added configuration for '{0}' to the start of the configuration file", id); break; case ComponentPosition.Placement.End: rootNode.InsertAfter(configNode, rootNode.ChildNodes[rootNode.ChildNodes.Count - 1]); this.ReportProgress(" Added configuration for '{0}' to the end of the configuration file", id); break; case ComponentPosition.Placement.Before: if(matchingNodes.Count < position.AdjustedInstance) this.ReportProgress(" Could not find configuration '{0}' (instance {1}) to add " + "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id); else { rootNode.InsertBefore(configNode, matchingNodes[position.AdjustedInstance - 1]); this.ReportProgress(" Added configuration for '{0}' before '{1}' (instance {2})", id, replaceId, position.AdjustedInstance); } break; default: // After if(matchingNodes.Count < position.AdjustedInstance) this.ReportProgress(" Could not find configuration '{0}' (instance {1}) to add " + "configuration for '{2}' so it will be omitted.", replaceId, position.AdjustedInstance, id); else { rootNode.InsertAfter(configNode, matchingNodes[position.AdjustedInstance - 1]); this.ReportProgress(" Added configuration for '{0}' after '{1}' (instance {2})", id, replaceId, position.AdjustedInstance); } break; } }
internal void InsertExceptionMessageBeforeNode(DekiScriptEnv env, XmlNode parent, XmlNode reference, Location location, Exception exception) { if(Fallthrough) { throw exception; } if(exception is DekiScriptDocumentTooLargeException) { DekiScriptDocumentTooLargeException e = (DekiScriptDocumentTooLargeException)exception; // check if an error message was already embedded if(e.Handled) { throw exception; } e.Handled = true; } // check if environment has a __callstack variable DekiScriptList callstack = null; DekiScriptLiteral callstackVar; if(env.Vars.TryGetValue(DekiScriptEnv.CALLSTACK, out callstackVar)) { callstack = callstackVar as DekiScriptList; } XDoc warning = DekiScriptRuntime.CreateWarningFromException(callstack, location, exception); parent.InsertBefore(parent.OwnerDocument.ImportNode(warning.AsXmlNode, true), reference); if(exception is DekiScriptDocumentTooLargeException) { throw exception; } }