/// <summary> /// Initializes a new instance of the XmlTabPage class. /// </summary> /// <param name="definition">XML definition.</param> internal XmlTabPage( XmlElement definition) { string name = definition.Attributes[ "name" ].Value; string tooltip = definition.Attributes[ "tooltip" ].Value; _tab = new TabPage(); _tab.Text = name; _tab.ToolTipText = tooltip; _tab.Tag = this; _tab.DockPadding.All = Property.TabPadding; XmlAttribute _modesAttr = null; _invisibleElem = (XmlElement) definition.SelectSingleNode( "invisible", FormsNamespace.NamespaceManager ); if(_invisibleElem != null) { _modesAttr = _invisibleElem.Attributes[ "modes" ]; if(_modesAttr != null) _invisibleModes = _modesAttr.Value.Split( ',' ); //Isto tem de estar aqui para não estourar mais à frente por "No registered property handler" definition.RemoveChild(definition.SelectSingleNode( "invisible", FormsNamespace.NamespaceManager )); } _disabledElem = (XmlElement)definition.SelectSingleNode("disabled", FormsNamespace.NamespaceManager); if (_disabledElem != null) { _modesAttr = _disabledElem.Attributes["modes"]; if (_modesAttr != null) _disabledModes = _modesAttr.Value.Split(','); //Isto tem de estar aqui para não estourar mais à frente por "No registered property handler" definition.RemoveChild(definition.SelectSingleNode("disabled", FormsNamespace.NamespaceManager)); } }
/// <summary>Removes attributes, comments, and processing instructions. </summary> private static void clean(System.Xml.XmlElement elem) { System.Xml.XmlNodeList children = elem.ChildNodes; for (int i = 0; i < children.Count; i++) { System.Xml.XmlNode child = children.Item(i); if (System.Convert.ToInt16(child.NodeType) == (short)System.Xml.XmlNodeType.ProcessingInstruction || System.Convert.ToInt16(child.NodeType) == (short)System.Xml.XmlNodeType.Comment) { elem.RemoveChild(child); } else if (System.Convert.ToInt16(child.NodeType) == (short)System.Xml.XmlNodeType.Element) { clean((System.Xml.XmlElement)child); } } System.Xml.XmlNamedNodeMap attributes = (System.Xml.XmlAttributeCollection)elem.Attributes; //get names System.String[] names = new System.String[attributes.Count]; for (int i = 0; i < names.Length; i++) { names[i] = attributes.Item(i).Name; } //remove by name for (int i = 0; i < names.Length; i++) { attributes.RemoveNamedItem(names[i]); } }
private static void RemoveXmlDeclaration(XmlElement element) { XmlNode declaration = element.FirstChild; while (declaration != null && declaration.NodeType != XmlNodeType.XmlDeclaration) declaration = declaration.NextSibling; if (declaration != null) element.RemoveChild(declaration); }
private static void DeleteAlbumsWithPrice(XmlElement root, double price) { foreach (XmlNode album in root.SelectNodes("album")) { double albumPrice = double.Parse(album["price"].InnerText); if (albumPrice > price) { root.RemoveChild(album); } } }
private static void ExpensiveMusicDeletor(double TriggerPrice, XmlElement rootNode) { var albums = rootNode.SelectNodes("album"); foreach (XmlElement album in albums) { if (double.Parse(album["price"].InnerText) > TriggerPrice) { rootNode.RemoveChild(album); } } }
private static void DeleteAlbum(XmlElement element, double maxPrice) { foreach (XmlElement album in element.ChildNodes) { var xmlPrice = album["price"].InnerText; var price = double.Parse(xmlPrice); if (price > maxPrice) { element.RemoveChild(album); } } }
private static void DeleteAlbumsWithGivenPrice(XmlElement root, double maxPrice) { foreach (XmlElement album in root.ChildNodes) { var xmlPrice = album["price"].InnerText; var parsedXmlPrice = double.Parse(xmlPrice); if (parsedXmlPrice > maxPrice) { root.RemoveChild(album); } } }
private static void DeliteAlbumByMaxPrice(XmlElement root, double maxPrice) { foreach (XmlElement album in root.ChildNodes) { string xmlPrice = album["price"].InnerText; double price = double.Parse(xmlPrice, CultureInfo.InvariantCulture); if (price > maxPrice) { root.RemoveChild(album); } } }
private static void DeleteAlbumsWithPrice(XmlElement root) { foreach (XmlElement album in root.SelectNodes("album")) { string xmlPrice = album["price"].InnerText; double price = double.Parse(xmlPrice); if (price > 20) { root.RemoveChild(album); } } }
private void SortAttributes (XmlElement el) { SortAttributesAttributes (el); ArrayList al = new ArrayList (); foreach (XmlNode n in el.ChildNodes) { if (n.NodeType == XmlNodeType.Element) SortAttributes (n as XmlElement); if (n.NodeType == XmlNodeType.Comment) al.Add (n); } foreach (XmlNode n in al) el.RemoveChild (n); }
private static void DeleteAlbumsWithBiggerPrice(XmlElement catalogue, decimal price) { var albums = catalogue.SelectNodes("album"); foreach (XmlElement album in albums) { var currentPriceAsString = album["price"].InnerText; var currentPriceAsDecimal = decimal.Parse(currentPriceAsString); if(currentPriceAsDecimal > price) { catalogue.RemoveChild(album); } } }
private static void DeleteElementAboveSpecificValue(XmlElement root, double maxValue, string value) { var elements = root.SelectNodes("album"); foreach (XmlElement item in elements) { var itemValue = item[value].InnerText; var parcedItemValue = double.Parse(itemValue); if (parcedItemValue > maxValue) { root.RemoveChild(item); } } }
private void RemoveExistingGeneratedItems(XmlElement folderNode) { List<XmlElement> elemstoRemove = new List<XmlElement>(); foreach (XmlElement elm in folderNode.ChildNodes) { if (elm.Name == "Compile") { if (elm.Attributes["Include"].Value.StartsWith(GenerationContext.ProjectFolder)) elemstoRemove.Add(elm); } } foreach (XmlElement elm in elemstoRemove) { folderNode.RemoveChild(elm); } }
private static void DeleteAlbumsWithPriceBiggerThan(XmlElement root, double maxPrice) { XmlNodeList childNodes = root.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { XmlNode album = childNodes[i]; string xmlPrice = album["price"].InnerText; double price = double.Parse(xmlPrice); if (maxPrice < price) { root.RemoveChild(album); } } }
private static void DeleteAlbumsWithPrice(XmlElement root, double maxPrice) { var childNodes = root.ChildNodes; for (int a = childNodes.Count - 1; a >= 0; a--) { var album = childNodes[a]; var xmlPrice = album["price"].InnerText; var price = double.Parse(xmlPrice); if (price > maxPrice) { root.RemoveChild(album); } } }
private static void DeleteAlbumsWithPriceGreaterThan(XmlElement catalogue, int price) { var albums = catalogue.ChildNodes; var albumsToRemove = new List<XmlNode>(); foreach (XmlNode album in albums) { var currenAlbumPrice = double.Parse(album.SelectSingleNode("price").InnerText); if (currenAlbumPrice > price) { albumsToRemove.Add(album); //catalogue.RemoveChild(album); } } foreach (XmlNode album in albumsToRemove) { catalogue.RemoveChild(album); } }
public void RemoveOnlyChildAffectOnEnumeration () { document.LoadXml ("<foo><child1/></foo>"); element = document.DocumentElement; enumerator = element.GetEnumerator(); element.RemoveChild(element.FirstChild); Assert.AreEqual (enumerator.MoveNext(), false, "MoveNext should have failed."); }
private void RemoveEmptyElements(XmlElement elementNode) { List<XmlElement> removeChildren = new List<XmlElement>(); foreach (XmlNode child in elementNode.ChildNodes) { if (child is System.Xml.XmlElement) { if ((child.Name == "PropertyGroup" || child.Name == "ItemGroup") && (child.ChildNodes == null || child.ChildNodes.Count == 0)) { removeChildren.Add(child as XmlElement); } else { RemoveEmptyElements(child as XmlElement); } } } foreach (XmlElement element in removeChildren) { elementNode.RemoveChild(element); } }
public void RemoveChildAffectOnEnumeration () { document.LoadXml ("<foo><child1/><child2/></foo>"); element = document.DocumentElement; enumerator = element.GetEnumerator(); element.RemoveChild(element.FirstChild); enumerator.MoveNext(); Assert.AreEqual (((XmlElement)enumerator.Current).LocalName, "child2", "Expected child2 element."); }
public void RemoveChildAffectOnEnumerationWhenEnumeratorIsOnRemovedChild () { document.LoadXml ("<foo><child1/><child2/><child3/></foo>"); element = document.DocumentElement; enumerator = element.GetEnumerator (); enumerator.MoveNext (); enumerator.MoveNext (); Assert.AreEqual ("child2", ((XmlElement)enumerator.Current).LocalName, "Expected child2 element."); Assert.AreEqual ("child2", element.FirstChild.NextSibling.LocalName, "Expected child2 element."); element.RemoveChild (element.FirstChild.NextSibling); enumerator.MoveNext (); try { element = (XmlElement) enumerator.Current; Assert.Fail ("Expected an InvalidOperationException."); } catch (InvalidOperationException) { } }
internal static bool FindPolicyElement (XmlElement root, QName name, bool removeWhenFound, out XmlElement element) { XmlElement policy = null; foreach (var node in root.ChildNodes) { var e = node as XmlElement; if (e == null) continue; if (!PolicyNS.Equals (e.NamespaceURI) || !e.LocalName.Equals ("Policy")) { element = null; return false; } if (policy != null) { element = null; return false; } policy = e; } if (policy == null) { element = null; return true; } element = null; foreach (var node in policy.ChildNodes) { var e = node as XmlElement; if (e == null) continue; if (!name.Namespace.Equals (e.NamespaceURI) || !name.Name.Equals (e.LocalName)) continue; element = e; break; } if (!removeWhenFound || (element == null)) return true; policy.RemoveChild (element); bool foundAnother = false; foreach (var node in policy.ChildNodes) { var e = node as XmlElement; if (e != null) { foundAnother = true; break; } } if (!foundAnother) root.RemoveChild (policy); return true; }
private void CleanGenerated(XmlElement group, string p) { List<XmlElement> toRemove = new List<XmlElement>(); foreach (XmlElement el in group.ChildNodes) { if (el.LocalName == p) { if (el.HasAttribute("Include")) { if (el.GetAttribute("Include").StartsWith("GeneratedConverters")) toRemove.Add(el); } } } foreach (XmlElement el in toRemove) { group.RemoveChild(el); } }
static void RecursiveInsertDoozerList(XmlElement e, List<XmlElement> doozers, List<XmlElement> conditionList) { List<XmlNode> oldChilds = new List<XmlNode>(); int foundMark = 0; foreach (XmlNode node in e) { if (foundMark > 0) { oldChilds.Add(node); } else { if (node.Value != null) { if (node.Value.Trim() == "!!! INSERT DOOZER LIST !!!") { foundMark = 1; } else if (node.Value.Trim() == "!!! INSERT CONDITION ATTRIBUTES !!!") { foundMark = 2; } } } } if (foundMark == 1) { foreach (XmlNode node in oldChilds) { e.RemoveChild(node); } foreach (XmlElement doozer in doozers) { CreateChild(e, "element").SetAttribute("ref", doozer.GetAttribute("shortname")); } } else if (foundMark == 2) { foreach (XmlNode node in oldChilds) { e.RemoveChild(node); } // create list of attributes List<string> attributes = new List<string>(); foreach (XmlElement condition in conditionList) { foreach (XmlElement attribute in condition) { if (attribute.Name == "attribute") { if (!attributes.Contains(attribute.GetAttribute("name"))) { attributes.Add(attribute.GetAttribute("name")); } } } } attributes.Sort(); foreach (string attribute in attributes) { XmlElement ae = CreateChild(e, "attribute"); ae.SetAttribute("name", attribute); ae.SetAttribute("type", "xs:string"); ae.SetAttribute("use", "optional"); } } else { foreach (XmlNode node in e) { if (node is XmlElement) RecursiveInsertDoozerList((XmlElement)node, doozers, conditionList); } } }
private void OnDataTableRowRollback(DataRowChangeEventArgs args) { if (!raiseDataSetEvents) { return; } bool escapedRaiseDocumentEvents = raiseDocumentEvents; raiseDocumentEvents = false; try { DataRow r = args.Row; XmlElement el = GetElementFromRow(r); if (el == null) { return; } DataTable tab = r.Table; ArrayList al = new ArrayList(); foreach (XmlAttribute attr in el.Attributes) { DataColumn col = tab.Columns [XmlHelper.Decode(attr.LocalName)]; if (col != null) { if (r.IsNull(col)) { // should be removed al.Add(attr); } else { attr.Value = r [col].ToString(); } } } foreach (XmlAttribute attr in al) { el.RemoveAttributeNode(attr); } al.Clear(); foreach (XmlNode child in el.ChildNodes) { if (child.NodeType == XmlNodeType.Element) { DataColumn col = tab.Columns [XmlHelper.Decode(child.LocalName)]; if (col != null) { if (r.IsNull(col)) { al.Add(child); } else { child.InnerText = r [col].ToString(); } } } } foreach (XmlNode n in al) { el.RemoveChild(n); } } finally { raiseDocumentEvents = escapedRaiseDocumentEvents; } }
protected override void ExecuteTask() { if (System.IO.Directory.Exists(workdir) == false) { System.IO.Directory.CreateDirectory(workdir); } if (workdir.EndsWith("\\") == false) { workdir += "\\"; } workdir = workdir.ToLower(); // 마스터 디스크립터를 기록하자 // 알아먹기 쉽게 일단 xml로 System.Collections.ArrayList files = new System.Collections.ArrayList(); // 리스트 foreach (string path in System.IO.Directory.GetFiles(workdir, "*", System.IO.SearchOption.AllDirectories)) { if (path.Contains("\\.svn\\") == false && System.IO.Path.GetFileName(path).ToLower() != System.IO.Path.GetFileName(filename).ToLower()) { files.Add(path.ToLower().Replace(workdir, "")); } } System.Xml.XmlDocument desc = new System.Xml.XmlDocument(); if (System.IO.File.Exists(filename) == true) { desc.Load(filename); } else { desc.AppendChild(desc.CreateNode(System.Xml.XmlNodeType.XmlDeclaration, "", "")); } System.Xml.XmlElement patchinfo = (System.Xml.XmlElement)desc.SelectSingleNode("Patchinfo"); if (patchinfo == null) { patchinfo = desc.CreateElement("Patchinfo"); desc.AppendChild(patchinfo); } System.Xml.XmlElement revisions = (System.Xml.XmlElement)patchinfo.SelectSingleNode("Revisions"); if (revisions == null) { revisions = desc.CreateElement("Revisions"); patchinfo.AppendChild(revisions); } System.Xml.XmlElement packing = (System.Xml.XmlElement)revisions.SelectSingleNode("Packing"); if (packing == null) { packing = desc.CreateElement("Packing"); packing.SetAttribute("Revision", "0"); revisions.AppendChild(packing); } System.Xml.XmlElement client = (System.Xml.XmlElement)revisions.SelectSingleNode("Client"); if (client == null) { client = desc.CreateElement("Client"); client.SetAttribute("Revision", "0"); revisions.AppendChild(client); } System.Xml.XmlElement patcher = (System.Xml.XmlElement)revisions.SelectSingleNode("Patcher"); if (patcher == null) { patcher = desc.CreateElement("Patcher"); patcher.SetAttribute("Revision", "0"); revisions.AppendChild(patcher); } System.Xml.XmlElement patch = (System.Xml.XmlElement)revisions.SelectSingleNode("Patch"); if (patch == null) { patch = desc.CreateElement("Patch"); patch.SetAttribute("Revision", "0"); revisions.AppendChild(patch); } System.Xml.XmlElement filesnode = (System.Xml.XmlElement)patchinfo.SelectSingleNode("Files"); if (filesnode != null) { patchinfo.RemoveChild(filesnode); } filesnode = desc.CreateElement("Files"); patchinfo.AppendChild(filesnode); foreach (string path in files) { System.Xml.XmlElement file = desc.CreateElement("File"); System.IO.FileInfo fi = new System.IO.FileInfo(System.IO.Path.Combine(workdir, path)); file.SetAttribute("Name", path); file.SetAttribute("Size", fi.Length.ToString()); Kom2.NET.Komfile kom = new Kom2.NET.Komfile(); if (kom.Open(System.IO.Path.Combine(workdir, path)) == true) { file.SetAttribute("Checksum", string.Format("{0:x8}", kom.Adler32)); file.SetAttribute("FileTime", string.Format("{0:x8}", kom.FileTime)); kom.Close(); } else { file.SetAttribute("Checksum", string.Format("{0:x8}", Kom2.NET.AdlerCheckSum.GetAdler32(System.IO.Path.Combine(workdir, path)))); file.SetAttribute("FileTime", "0"); } filesnode.AppendChild(file); } if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filename)) == false) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filename)); } desc.Save(filename); }
/// <summary> /// Inspects a RadioGroup element. /// </summary> /// <param name="element">The RadioGroup element to inspect.</param> private void InspectRadioGroupElement(XmlElement element) { XmlElement radioButtonGroup = element.OwnerDocument.CreateElement("RadioButtonGroup", element.NamespaceURI); this.OnError(InspectorTestType.RadioGroupDeprecated, element, "The RadioGroup element is deprecated. Use RadioButtonGroup instead."); element.ParentNode.InsertAfter(radioButtonGroup, element); element.ParentNode.RemoveChild(element); // move all the attributes from the old element to the new element while (element.Attributes.Count > 0) { XmlAttribute attribute = element.Attributes[0]; element.Attributes.Remove(attribute); radioButtonGroup.Attributes.Append(attribute); } // move all the attributes from the old element to the new element while (element.ChildNodes.Count > 0) { XmlNode node = element.ChildNodes[0]; element.RemoveChild(node); radioButtonGroup.AppendChild(node); } }
internal XmlElement SchemaTree(XmlDocument xd, DataTable dt) { dsElement = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); ConstraintNames = new ArrayList(); _ds = dt.DataSet; _dc = xd; namespaces = new Hashtable(); prefixes = new Hashtable(); if (schFormat != SchemaFormat.Remoting) { autogenerated = new Hashtable(); } XmlElement rootSchema = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); _sRoot = rootSchema; WriteSchemaRoot(xd, rootSchema, dt.Namespace); XmlElement dsCompositor = FillDataSetElement(xd, null, dt); constraintSeparator = xd.CreateElement(Keywords.XSD_PREFIX, "SHOULDNOTBEHERE", Keywords.XSDNS); dsElement.AppendChild(constraintSeparator); if (schFormat != SchemaFormat.Remoting) { if (_ds != null) { namespaces[_ds.Namespace] = rootSchema; if (_ds.Namespace.Length == 0) { prefixes[_ds.Namespace] = null; } else { // generate a prefix for the dataset schema itself. rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, _ds.Namespace ); prefixes[_ds.Namespace] = "mstns"; } } else { namespaces[dt.Namespace] = rootSchema; if (dt.Namespace.Length == 0) { prefixes[dt.Namespace] = null; } else { // generate a prefix for the dataset schema itself. rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, dt.Namespace ); prefixes[dt.Namespace] = "mstns"; } } } // Generate all the constraint names GenerateConstraintNames(dt, true); // // Output all top level elements, which will recursively invoke to other tables. // XmlElement el = HandleTable(dt, xd, rootSchema, false); rootSchema.AppendChild(el); dsElement.RemoveChild(constraintSeparator); rootSchema.AppendChild(dsElement); return rootSchema; }
internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet ds, DataTable dt, bool writeHierarchy) { ConstraintNames = new ArrayList(); autogenerated = new Hashtable(); bool genSecondary = filePath != null; //null non-file based streams. dsElement = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); DataTable [] top; bool fFlat = false; DataTable _dt = dt; if (ds != null) { _ds = ds; foreach(DataTable table in ds.Tables) { _tables.Add(table); } } else { if (dt.DataSet != null) { // preserve datatable's dataset to use for xml // if null it would write out document element instead of dt.DataSet.DataSetName _ds = dt.DataSet; } _tables.Add(dt); if (writeHierarchy) { CreateTablesHierarchy(dt); } } _dc = xd; namespaces = new Hashtable(); prefixes = new Hashtable(); XmlElement rootSchema = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); _sRoot = rootSchema; // Need to writeid attribute on schema, as webservice relys on it for typeddataset deserialization // to get class name if (_ds != null) { rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName(_ds.DataSetName)); } else { rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName("NewDataSet")); } if (_ds != null) { WriteSchemaRoot(xd, rootSchema, _ds.Namespace); } else { WriteSchemaRoot(xd, rootSchema, _dt.Namespace); } // register the root element and associated NS if (schFormat == SchemaFormat.Remoting) { if (_ds != null) { namespaces[_ds.Namespace] = rootSchema; } else { namespaces[_dt.Namespace] = rootSchema; } } if (schFormat != SchemaFormat.Remoting) { if (_ds != null) { namespaces[_ds.Namespace] = rootSchema; if (_ds.Namespace.Length == 0) prefixes[_ds.Namespace] = null; else { // generate a prefix for the dataset schema itself. rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, _ds.Namespace ); prefixes[_ds.Namespace] = "mstns"; } } } // Generate all the constraint names if (ds != null) GenerateConstraintNames(ds); else GenerateConstraintNames(_tables); // Setup AutoGenerated table if (schFormat != SchemaFormat.Remoting) { if (ds != null) { SetupAutoGenerated(ds); } else { SetupAutoGenerated(_tables); } } // // Output all top level elements, which will recursively invoke to other tables. // top = ((ds != null) ? ds.TopLevelTables(true) : CreateToplevelTables()); if (top.Length == 0 || schFormat == SchemaFormat.WebServiceSkipSchema || schFormat == SchemaFormat.RemotingSkipSchema) { // return an empty schema for now. // probably we need to throw an exception FillDataSetElement(xd, ds, dt); rootSchema.AppendChild(dsElement); AddXdoProperties(_ds, dsElement, xd ); AddExtendedProperties(ds.extendedProperties, dsElement); xd.AppendChild(rootSchema); xd.Save(xmlWriter); xmlWriter.Flush(); return ; // rootSchema content has already been pushed to xmlWriter } // if (schFormat != SchemaFormat.WebService && namespaces.Count > 1 && !genSecondary) { // rootSchema.SetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS, namespaces.Count.ToString()); // } // Fill out dataset element XmlElement dsCompositor = FillDataSetElement(xd, ds, dt); constraintSeparator = xd.CreateElement(Keywords.XSD_PREFIX, "SHOULDNOTBEHERE", Keywords.XSDNS); dsElement.AppendChild(constraintSeparator); // DataSet properties if (_ds != null) { AddXdoProperties(_ds, dsElement, xd ); AddExtendedProperties(_ds.extendedProperties, dsElement); } for (int i = 0; i < top.Length; i++) { XmlElement el = HandleTable(top[i], xd, rootSchema); if (((_ds != null )&& (_ds.Namespace == top[i].Namespace)) || Common.ADP.IsEmpty(top[i].Namespace) || (schFormat == SchemaFormat.Remoting)) { bool fNestedInDataset = top[i].fNestedInDataset; if (((_ds != null )&& (_ds.Namespace.Length != 0)) && Common.ADP.IsEmpty(top[i].Namespace)) { fNestedInDataset = true; } // what if dt has two nested relation , one self nested , the other with dtParent if (top[i].SelfNested) { // regarding above check : is it selfnested! fNestedInDataset = false; } if (top[i].NestedParentsCount > 1) { // if it has multiple parents, it should be global fNestedInDataset = false; } if(fNestedInDataset) { //deal with maxOccurs properly if (top[i].MinOccurs != 1) { el.SetAttribute(Keywords.MINOCCURS, top[i].MinOccurs.ToString(CultureInfo.InvariantCulture)); } if (top[i].MaxOccurs == -1){ el.SetAttribute(Keywords.MAXOCCURS, Keywords.ZERO_OR_MORE); } else if (top[i].MaxOccurs != 1){ el.SetAttribute(Keywords.MAXOCCURS, top[i].MaxOccurs.ToString(CultureInfo.InvariantCulture)); } } if (!fNestedInDataset) { rootSchema.AppendChild(el); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); if ((_ds != null && _ds.Namespace == top[i].Namespace) || Common.ADP.IsEmpty(top[i].Namespace) || (schFormat == SchemaFormat.Remoting)) node.SetAttribute(Keywords.REF, top[i].EncodedTableName); else node.SetAttribute(Keywords.REF, ((string)prefixes[top[i].Namespace])+':'+top[i].EncodedTableName); dsCompositor.AppendChild(node); } else dsCompositor.AppendChild(el); } else { AppendChildWithoutRef(rootSchema, top[i].Namespace, el, Keywords.XSD_ELEMENT); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); node.SetAttribute(Keywords.REF, ((string)prefixes[top[i].Namespace])+':'+top[i].EncodedTableName); dsCompositor.AppendChild(node); } } dsElement.RemoveChild(constraintSeparator); rootSchema.AppendChild(dsElement); // Output all non-heirarchical relations without constraints DataRelation [] rels = new DataRelation[0]; if (ds != null && _tables.Count> 0) { // we need to make sure we want to write relation just for tables in list rels = new DataRelation[ds.Relations.Count]; for (int i = 0 ; i < ds.Relations.Count ; i++) { rels[i] = ds.Relations[i]; } } else if (writeHierarchy && _tables.Count > 0 ) { CreateRelations((DataTable)_tables[0]); rels = new DataRelation[_relations.Count]; _relations.CopyTo(rels, 0); } XmlElement nodeAnn = null; XmlElement nodeApp = null; for (int i = 0; i < rels.Length; ++i) { DataRelation rel = rels[i]; if (!rel.Nested || fFlat) { if (rel.ChildKeyConstraint == null) { if (nodeAnn == null) { nodeAnn = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ANNOTATION, Keywords.XSDNS); rootSchema.AppendChild(nodeAnn); nodeApp = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_APPINFO, Keywords.XSDNS); nodeAnn.AppendChild(nodeApp); } Debug.Assert(nodeApp != null, "Need to create <application..> node first."); nodeApp.AppendChild(HandleRelation(rel, xd)); } } } XmlComment comment = null; bool isMultipleNamespaceAndStreamingWriter = (namespaces.Count > 1 && !genSecondary); if (schFormat != SchemaFormat.Remoting && schFormat != SchemaFormat.RemotingSkipSchema) { // complete processing of rootSchema foreach (string ns in namespaces.Keys) { if (ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace) || Common.ADP.IsEmpty(ns)) { continue; } XmlElement _import = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_IMPORT, Keywords.XSDNS); _import.SetAttribute(Keywords.XSD_NAMESPACE, ns); if ( schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter) { _import.SetAttribute(Keywords.XSD_SCHEMALOCATION, fileName + "_" + prefixes[ns] + ".xsd"); } ((XmlNode)rootSchema).PrependChild((XmlNode)_import); } if (schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter) { rootSchema.SetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS, namespaces.Count.ToString(CultureInfo.InvariantCulture)); } // Post rootSchema content to xmlWriter. xd.AppendChild(rootSchema); // KB if (schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter) { xd.WriteTo(xmlWriter); } else { xd.Save(xmlWriter); } xd.RemoveChild(rootSchema); //KB foreach(string ns in namespaces.Keys) { if (ns == ((_ds != null)?_ds.Namespace:_dt.Namespace) || Common.ADP.IsEmpty(ns)) { continue; } XmlWriter xw = null; if (!genSecondary) { xw = xmlWriter; } else { xw = new XmlTextWriter(filePath + fileName + "_" + prefixes[ns] + ".xsd", null); } try { if (genSecondary) { if (xw is XmlTextWriter) { ((XmlTextWriter)xw).Formatting = Formatting.Indented; } xw.WriteStartDocument(true); } XmlElement tNode = (XmlElement) namespaces[ns] ; _dc.AppendChild( tNode ); foreach(string imp_ns in namespaces.Keys) { if (ns == imp_ns) { continue; // don't write out yourself } string prefix = (string) prefixes[imp_ns]; if (prefix == null) { // only for dataset.Namespace == empty continue; // do nothing } tNode.SetAttribute("xmlns:"+prefix, imp_ns); XmlElement _import2 = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_IMPORT, Keywords.XSDNS); _import2.SetAttribute(Keywords.XSD_NAMESPACE, imp_ns); if ( schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter) { if (imp_ns == ((_ds != null)?_ds.Namespace:_dt.Namespace)) _import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, fileName + fileExt); // for the dataset namespace don't append anything else _import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, fileName + "_" + prefix +".xsd"); } ((XmlNode)tNode).PrependChild((XmlNode)_import2); } if (schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter) { _dc.WriteTo(xw); } else { _dc.Save(xw); } _dc.RemoveChild( tNode ); if (genSecondary) { xw.WriteEndDocument(); } } finally { if (genSecondary) { xw.Close(); } } } } else { xd.AppendChild(rootSchema); xd.Save(xmlWriter); } if (comment != null) { ((XmlNode)rootSchema).PrependChild((XmlNode)comment); } if (!genSecondary) { xmlWriter.Flush(); } return;// rootSchema; }
public static void RemoveElement(XmlElement parent, string tag) { if (parent == null) return; XmlNodeList nl = parent.GetElementsByTagName(tag); XmlNode[] children = new XmlNode[nl.Count]; for (int i = 0; i < children.Length; i++) children[i] = nl.Item(i); foreach (XmlNode child in children) parent.RemoveChild(child); }
// This removes all children of an element. internal static void RemoveAllChildren (XmlElement inputElement) { XmlNode child = inputElement.FirstChild; XmlNode sibling = null; while (child != null) { sibling = child.NextSibling; inputElement.RemoveChild(child); child = sibling; } }
void CleanDescription(XmlElement parent) { ArrayList todelete = new ArrayList (); foreach (XmlNode nod in parent.ChildNodes) { XmlElement elem = nod as XmlElement; if (elem == null) continue; if (elem.LocalName == "Module") CleanDescription (elem); else if (elem.LocalName != "Dependencies" && elem.LocalName != "Runtime") todelete.Add (elem); } foreach (XmlElement e in todelete) parent.RemoveChild (e); }
private void RemoveComments(XmlElement element) { List<XmlComment> comments = new List<XmlComment>(); foreach (XmlNode childElement in element.ChildNodes) { if (childElement is XmlComment) comments.Add((XmlComment)childElement); } foreach (XmlComment comment in comments) { XmlWhitespace prev = comment.PreviousSibling as XmlWhitespace; XmlWhitespace next = comment.NextSibling as XmlWhitespace; if (prev != null && prev.Value != null & prev.Value.StartsWith(Environment.NewLine) && next != null && next.Value != null && next.Value.StartsWith(Environment.NewLine)) { element.RemoveChild(next); } element.RemoveChild(comment); } foreach (XmlNode childElement in element.ChildNodes) { if (childElement is XmlElement && childElement.HasChildNodes) { RemoveComments((XmlElement)childElement); } } }
static void SearchAndReplaceInParagraph(XmlElement paragraph, string search, string replace, bool matchCase) { XmlDocument xmlDoc = paragraph.OwnerDocument; string wordNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("w", wordNamespace); XmlNodeList paragraphText = paragraph.SelectNodes("descendant::w:t", nsmgr); StringBuilder sb = new StringBuilder(); foreach (XmlNode text in paragraphText) sb.Append(((XmlElement)text).InnerText); if (sb.ToString().Contains(search) || (!matchCase && sb.ToString().ToUpper().Contains(search.ToUpper()))) { XmlNodeList runs = paragraph.SelectNodes("child::w:r", nsmgr); foreach (XmlElement run in runs) { XmlNodeList childElements = run.SelectNodes("child::*", nsmgr); if (childElements.Count > 0) { XmlElement last = (XmlElement)childElements[childElements.Count - 1]; for (int c = childElements.Count - 1; c >= 0; --c) { if (childElements[c].Name == "w:rPr") continue; if (childElements[c].Name == "w:t") { string textElementString = childElements[c].InnerText; for (int i = textElementString.Length - 1; i >= 0; --i) { XmlElement newRun = xmlDoc.CreateElement("w:r", wordNamespace); XmlElement runProps = (XmlElement)run.SelectSingleNode("child::w:rPr", nsmgr); if (runProps != null) { XmlElement newRunProps = (XmlElement)runProps.CloneNode(true); newRun.AppendChild(newRunProps); } XmlElement newTextElement = xmlDoc.CreateElement("w:t", wordNamespace); XmlText newText = xmlDoc.CreateTextNode(textElementString[i].ToString()); newTextElement.AppendChild(newText); if (textElementString[i] == ' ') { XmlAttribute xmlSpace = xmlDoc.CreateAttribute( "xml", "space", "http://www.w3.org/XML/1998/namespace"); xmlSpace.Value = "preserve"; newTextElement.Attributes.Append(xmlSpace); } newRun.AppendChild(newTextElement); paragraph.InsertAfter(newRun, run); } } else { XmlElement newRun = xmlDoc.CreateElement("w:r", wordNamespace); XmlElement runProps = (XmlElement)run.SelectSingleNode("child::w:rPr", nsmgr); if (runProps != null) { XmlElement newRunProps = (XmlElement)runProps.CloneNode(true); newRun.AppendChild(newRunProps); } XmlElement newChildElement = (XmlElement)childElements[c].CloneNode(true); newRun.AppendChild(newChildElement); paragraph.InsertAfter(newRun, run); } } paragraph.RemoveChild(run); } } while (true) { bool cont = false; runs = paragraph.SelectNodes("child::w:r", nsmgr); for (int i = 0; i <= runs.Count - search.Length; ++i) { bool match = true; for (int c = 0; c < search.Length; ++c) { XmlElement textElement = (XmlElement)runs[i + c].SelectSingleNode("child::w:t", nsmgr); if (textElement == null) { match = false; break; } if (textElement.InnerText == search[c].ToString()) continue; if (!matchCase && textElement.InnerText.ToUpper() == search[c].ToString().ToUpper()) continue; match = false; break; } if (match) { XmlElement runProps = (XmlElement)runs[i].SelectSingleNode("descendant::w:rPr", nsmgr); XmlElement newRun = xmlDoc.CreateElement("w:r", wordNamespace); if (runProps != null) { XmlElement newRunProps = (XmlElement)runProps.CloneNode(true); newRun.AppendChild(newRunProps); } XmlElement newTextElement = xmlDoc.CreateElement("w:t", wordNamespace); XmlText newText = xmlDoc.CreateTextNode(replace); newTextElement.AppendChild(newText); if (replace[0] == ' ' || replace[replace.Length - 1] == ' ') { XmlAttribute xmlSpace = xmlDoc.CreateAttribute("xml", "space", "http://www.w3.org/XML/1998/namespace"); xmlSpace.Value = "preserve"; newTextElement.Attributes.Append(xmlSpace); } newRun.AppendChild(newTextElement); paragraph.InsertAfter(newRun, (XmlNode)runs[i]); for (int c = 0; c < search.Length; ++c) paragraph.RemoveChild(runs[i + c]); cont = true; break; } } if (!cont) break; } // Consolidate adjacent runs that have only text elements, and have the // same run properties. This isn't necessary to create a valid document, // however, having the split runs is a bit messy. XmlNodeList children = paragraph.SelectNodes("child::*", nsmgr); List<int> matchId = new List<int>(); int id = 0; for (int c = 0; c < children.Count; ++c) { if (c == 0) { matchId.Add(id); continue; } if (children[c].Name == "w:r" && children[c - 1].Name == "w:r" && children[c].SelectSingleNode("w:t", nsmgr) != null && children[c - 1].SelectSingleNode("w:t", nsmgr) != null) { XmlElement runProps = (XmlElement)children[c].SelectSingleNode("w:rPr", nsmgr); XmlElement lastRunProps = (XmlElement)children[c - 1].SelectSingleNode("w:rPr", nsmgr); if ((runProps == null && lastRunProps != null) || (runProps != null && lastRunProps == null)) { matchId.Add(++id); continue; } if (runProps != null && runProps.InnerXml != lastRunProps.InnerXml) { matchId.Add(++id); continue; } matchId.Add(id); continue; } matchId.Add(++id); } for (int i = 0; i <= id; ++i) { var x1 = matchId.IndexOf(i); var x2 = matchId.LastIndexOf(i); if (x1 == x2) continue; StringBuilder sb2 = new StringBuilder(); for (int z = x1; z <= x2; ++z) sb2.Append(((XmlElement)children[z] .SelectSingleNode("w:t", nsmgr)).InnerText); XmlElement newRun = xmlDoc.CreateElement("w:r", wordNamespace); XmlElement runProps = (XmlElement)children[x1].SelectSingleNode("child::w:rPr", nsmgr); if (runProps != null) { XmlElement newRunProps = (XmlElement)runProps.CloneNode(true); newRun.AppendChild(newRunProps); } XmlElement newTextElement = xmlDoc.CreateElement("w:t", wordNamespace); XmlText newText = xmlDoc.CreateTextNode(sb2.ToString()); newTextElement.AppendChild(newText); if (sb2[0] == ' ' || sb2[sb2.Length - 1] == ' ') { XmlAttribute xmlSpace = xmlDoc.CreateAttribute( "xml", "space", "http://www.w3.org/XML/1998/namespace"); xmlSpace.Value = "preserve"; newTextElement.Attributes.Append(xmlSpace); } newRun.AppendChild(newTextElement); paragraph.InsertAfter(newRun, children[x2]); for (int z = x1; z <= x2; ++z) paragraph.RemoveChild(children[z]); } var txbxParagraphs = paragraph.SelectNodes("descendant::w:p", nsmgr); foreach (XmlElement p in txbxParagraphs) SearchAndReplaceInParagraph((XmlElement)p, search, replace, matchCase); } }