Example #1
0
        public static void Main()
        {
            string content = "<book genre='novel' ISBN='1-861001-57-5'>" +
                             "<title>Pride And Prejudice</title>" +
                             "</book>";

            Console.WriteLine(content);
            Console.WriteLine();

            //Create the XmlDocument.
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(content);

            //Create a deep clone.  The cloned node
            //includes the child node.
            XmlDocument deep = (XmlDocument)doc.CloneNode(true);

            Console.WriteLine(deep.Name);
            Console.WriteLine(deep.OuterXml);
            Console.WriteLine(deep.ChildNodes.Count);
            Console.WriteLine();

            //Create a shallow clone.  The cloned node does not
            //include the child node.
            XmlDocument shallow = (XmlDocument)doc.CloneNode(false);

            Console.WriteLine(shallow.Name);
            Console.WriteLine(shallow.OuterXml);
            Console.WriteLine(shallow.ChildNodes.Count);
            Console.WriteLine();

            Console.ReadLine();
        }
Example #2
0
        /// <summary>
        /// Method to obtain the username of an generic user profile
        /// </summary>
        /// <param name="educator"></param>
        /// <returns></returns>
        public static string GetEducatorUsername(string educator)
        {
            Console.WriteLine("---> In GetEducatorUsername");
            XmlDocument _document = new XmlDocument();

            byte[] bytes = File.ReadAllBytes("C:/w/EdgenuityFmwk/WebPage/DB_Layer/UsersRoles.xml");
            string xml   = Encoding.UTF8.GetString(bytes);

            try
            {
                _document.LoadXml(xml);
            }
            catch (XmlException e)
            {
                Console.WriteLine("Exception: ", e);
            }

            var doc = (XmlDocument)_document.CloneNode(true);

            XmlNodeList node = doc.GetElementsByTagName("//educators/" + educator + "/user");
            int         i    = 1;

            foreach (XmlNode nodeElement in node)
            {
                Console.WriteLine("---> Data:" + i + ":: " + nodeElement.Value);
                i++;
            }

            return(null);
        }
Example #3
0
        /// <summary>
        /// Root of the preprocessing.
        /// </summary>
        private XmlDocument Preprocess()
        {
            XmlDocument outerDocument = _project.Xml.XmlDocument;

            CreateImplicitImportTable();

            AddImplicitImportNodes(outerDocument.DocumentElement);

            XmlDocument destinationDocument = (XmlDocument)outerDocument.CloneNode(false /* shallow */);

            _filePaths.Push(_project.FullPath);

            if (!String.IsNullOrEmpty(_project.FullPath)) // Ignore in-memory projects
            {
                destinationDocument.AppendChild(destinationDocument.CreateComment("\r\n" + new String('=', 140) + "\r\n" + _project.FullPath.Replace("--", "__") + "\r\n" + new String('=', 140) + "\r\n"));
            }

            CloneChildrenResolvingImports(outerDocument, destinationDocument);

            // Remove the nodes that were added as implicit imports
            //
            foreach (XmlNode node in _addedNodes)
            {
                node.ParentNode?.RemoveChild(node);
            }

            return(destinationDocument);
        }
Example #4
0
 public virtual IDomDocument Clone()
 {
     lock (_document)
     {
         return(new DomDocumentImpl((XmlDocument)_document.CloneNode(true)));
     }
 }
Example #5
0
        public static void CloneComplexDocumentTrue()
        {
            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(ComplexDocument);
            var cloned = xmlDocument.CloneNode(true);

            Assert.NotSame(xmlDocument.ChildNodes, cloned.ChildNodes);
            Assert.Equal(xmlDocument.NodeType, cloned.NodeType);
            Assert.Equal(xmlDocument.ChildNodes.Count, cloned.ChildNodes.Count);
            Assert.Equal(xmlDocument.LastChild.Value, cloned.LastChild.Value);

            // Test XmlNode.LastChild
            {
                for (var i = 0; i < xmlDocument.ChildNodes.Count; i++)
                {
                    if (xmlDocument.ChildNodes[i].LastChild == null)
                    {
                        Assert.Equal(xmlDocument.ChildNodes[i].LastChild, cloned.ChildNodes[i].LastChild);
                    }
                    else
                    {
                        Assert.Equal(xmlDocument.ChildNodes[i].LastChild.Value, cloned.ChildNodes[i].LastChild.Value);
                    }
                }
            }

            // Test XmlNode.NextSibling
            {
                var count        = cloned.ChildNodes.Count;
                var previousNode = cloned.ChildNodes[0];

                for (var idx = 1; idx < count; idx++)
                {
                    var currentNode = cloned.ChildNodes[idx];
                    Assert.Equal(currentNode, previousNode.NextSibling);
                    previousNode = currentNode;
                }

                Assert.Null(previousNode.NextSibling);
            }

            // Test XmlNode.PreviousSibling
            {
                var count    = cloned.ChildNodes.Count;
                var nextNode = cloned.ChildNodes[count - 1];

                for (var idx = count - 2; idx >= 0; idx--)
                {
                    var currentNode = cloned.ChildNodes[idx];
                    Assert.Equal(currentNode, nextNode.PreviousSibling);
                    nextNode = currentNode;
                }

                Assert.Null(nextNode.PreviousSibling);
            }

            // Test XmlNode.ParentNode
            CheckChildren(cloned);
        }
        private XmlDocument UpdateDocumentVersion(XmlDocument document, Stream stream)
        {
            string innerText = document.SelectSingleNode("/Credentials/version").InnerText;

            if (innerText != "1.0")
            {
                throw new ArgumentException(string.Format("Cannot convert document version {0} to version {1}", (object)innerText, (object)"2.0"));
            }
            XmlDocument credentialsXmlDocument = document;

            try
            {
                XmlDocument xmlDocument = (XmlDocument)credentialsXmlDocument.CloneNode(true);
                xmlDocument.SelectSingleNode("/Credentials/version").InnerText = "2.0";
                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/Credentials/passwordEntry");
                if (xmlNodeList != null)
                {
                    foreach (XmlNode xmlNode in xmlNodeList)
                    {
                        char[] password = CredentialStore.UnobfuscatePassword(xmlNode["password"].InnerText, xmlNode["host"].InnerText, xmlNode["username"].InnerText);
                        xmlNode["password"].InnerText = CredentialStore.EncryptPassword(password);
                    }
                    credentialsXmlDocument = xmlDocument;
                    CredentialStore.SaveCredentialsDocument(credentialsXmlDocument, stream);
                }
            }
            catch
            {
            }
            return(credentialsXmlDocument);
        }
Example #7
0
        /// <summary>
        /// Returns a string representing the configured metadata for
        /// this service provider.  This will include key information
        /// as well if the metadata and extended metadata have this
        /// information specified.
        /// </summary>
        /// <param name="signMetadata">
        /// Flag to specify if the exportable metadata should be signed.
        /// </param>
        /// <returns>
        /// String with runtime representation of the metadata for this
        /// service provider.
        /// </returns>
        public string GetExportableMetadata(bool signMetadata)
        {
            var     exportableXml = (XmlDocument)_metadata.CloneNode(true);
            XmlNode entityDescriptorNode
                = exportableXml.SelectSingleNode("/md:EntityDescriptor", _metadataNsMgr);

            if (entityDescriptorNode == null)
            {
                throw new Saml2Exception(Resources.ServiceProviderEntityDescriptorNodeNotFound);
            }

            if (signMetadata && string.IsNullOrEmpty(SigningCertificateAlias))
            {
                throw new Saml2Exception(Resources.ServiceProviderCantSignMetadataWithoutCertificateAlias);
            }

            if (signMetadata)
            {
                XmlAttribute descriptorId = exportableXml.CreateAttribute("ID");
                descriptorId.Value = _saml2Utils.GenerateId();
                entityDescriptorNode.Attributes.Append(descriptorId);

                _saml2Utils.SignXml(SigningCertificateAlias, exportableXml, descriptorId.Value, true);
            }

            return(exportableXml.InnerXml);
        }
Example #8
0
        public static void CloneComplexDocumentTrue()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(ComplexDocument);
            var cloned = xmlDocument.CloneNode(true);

            Assert.NotSame(xmlDocument.ChildNodes, cloned.ChildNodes);
            Assert.Equal(xmlDocument.NodeType, cloned.NodeType);
            Assert.Equal(xmlDocument.ChildNodes.Count, cloned.ChildNodes.Count);
            Assert.Equal(xmlDocument.LastChild.Value, cloned.LastChild.Value);

            // Test XmlNode.LastChild
            {
                for (var i = 0; i < xmlDocument.ChildNodes.Count; i++)
                {
                    if (xmlDocument.ChildNodes[i].LastChild == null)
                    {
                        Assert.Equal(xmlDocument.ChildNodes[i].LastChild, cloned.ChildNodes[i].LastChild);
                    }
                    else
                    {
                        Assert.Equal(xmlDocument.ChildNodes[i].LastChild.Value, cloned.ChildNodes[i].LastChild.Value);
                    }
                }
            }

            // Test XmlNode.NextSibling
            {
                var count = cloned.ChildNodes.Count;
                var previousNode = cloned.ChildNodes[0];

                for (var idx = 1; idx < count; idx++)
                {
                    var currentNode = cloned.ChildNodes[idx];
                    Assert.Equal(currentNode, previousNode.NextSibling);
                    previousNode = currentNode;
                }

                Assert.Null(previousNode.NextSibling);
            }

            // Test XmlNode.PreviousSibling
            {
                var count = cloned.ChildNodes.Count;
                var nextNode = cloned.ChildNodes[count - 1];

                for (var idx = count - 2; idx >= 0; idx--)
                {
                    var currentNode = cloned.ChildNodes[idx];
                    Assert.Equal(currentNode, nextNode.PreviousSibling);
                    nextNode = currentNode;
                }

                Assert.Null(nextNode.PreviousSibling);
            }

            // Test XmlNode.ParentNode
            CheckChildren(cloned);
        }
Example #9
0
        public Form1(string[] args)
        {
            InitializeComponent();

            (xmlDoc).Load((args.Length > 0 && args[0] != null && ((string)(args[0])) != "." ? ((string)(args[0])) : ".\\Menu.xml"));

            if (xmlDoc.Attributes != null)
            {
                clockTick  = (xmlDoc.Attributes["clockTick"] != null ? Convert.ToInt32(xmlDoc.Attributes["clockTick"].Value) : clockTick);
                clockLimit = (xmlDoc.Attributes["clockLimit"] != null ? Convert.ToInt32(xmlDoc.Attributes["clockLimit"].Value) : clockLimit);
                clockRate  = (xmlDoc.Attributes["clockRate"] != null ? Convert.ToInt32(xmlDoc.Attributes["clockRate"].Value) : clockRate);
            }

            timer1.Interval = clockRate;

            if ((args.Length > 1 && args[1] != null && ((string)(args[1])) != "."))
            {
                switch (args[1])
                {
                default:
                    break;

                case "0":
                    break;

                case "1":

                    c         = new Credentials();
                    this.Text = this.Text + " - " + c.username;
                    break;
                }
            }
            // tabControl
            tabControl        = new System.Windows.Forms.TabControl();
            tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                                                                       | System.Windows.Forms.AnchorStyles.Left)
                                                                      | System.Windows.Forms.AnchorStyles.Right)));
            tabControl.Location      = new System.Drawing.Point(12, 12);
            tabControl.Margin        = new System.Windows.Forms.Padding(0);
            tabControl.Name          = "tabControl";
            tabControl.SelectedIndex = 0;
            tabControl.AllowDrop     = true;
            tabControl.Size          = new System.Drawing.Size(this.Size.Width - 40, this.Size.Height - 110);
            tabControl.TabIndex      = 0;
            Controls.Add(tabControl);
            processXML(xmlDoc.CloneNode(true), tabControl);
            this.AllowDrop  = true;
            this.DragDrop  += new System.Windows.Forms.DragEventHandler(this.Tab_DragDrop);
            this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Tab_DragEnter);

            label2.Text = TimeSpan.FromMilliseconds((UInt32)System.Environment.TickCount).Hours.ToString() + " hrs";

            sysinfo s = new sysinfo();

            progressBar1.Value = s.cpuUsage();
            progressBar2.Value = s.availableRam();
        }
Example #10
0
        public string GenerateHTML(ComputerModel model, string stylesheet = null)
        {
            XmlDocument html = (XmlDocument)HtmlTemplate.CloneNode(true);

            GenerateTitle(model, html);
            if (stylesheet != null)
            {
                ReplaceStylesheet(html, stylesheet);
            }
            XmlElement div = html.GetElementsByTagName("div").OfType <XmlElement>().First(e => e.GetAttribute("class") == "boxes");

            foreach (Pin pin in model.Pins.OrderBy(p => p.Offset))
            {
                XmlElement template = (XmlElement)CheckboxTemplate.DocumentElement.CloneNode(true);
                XmlElement input    = (XmlElement)template.GetElementsByTagName("input").Item(0);
                XmlElement label    = (XmlElement)template.GetElementsByTagName("label").Item(0);
                if (pin.Type == PinType.Intermediate)
                {
                    input.SetAttribute("class", "intermediate-box");
                    template.RemoveChild(label);
                }
                else
                {
                    if (pin.FirstOfType)
                    {
                        label.InnerText = string.Format(label.InnerText, pin.NameOfType);
                    }
                    else
                    {
                        template.RemoveChild(label);
                    }
                    if (pin.Type == PinType.Input)
                    {
                        input.SetAttribute("class", "input-box");
                    }
                    else
                    {
                        input.SetAttribute("class", "output-box");
                    }
                }
                foreach (XmlNode node in template.ChildNodes)
                {
                    div.AppendChild(html.ImportNode(node, true));
                }
            }
            StringBuilder str = new StringBuilder();

            str.AppendLine("<!DOCTYPE html>");
            XmlWriterSettings settings = new XmlWriterSettings {
                OmitXmlDeclaration = true
            };

            using (XmlWriter writer = XmlWriter.Create(str, settings)) {
                html.WriteTo(writer);
            }
            return(str.ToString());
        }
Example #11
0
 private XmlDocument Clone(XmlDocument xml)
 {
     Cloning?.Invoke();
     if (_origXml != null)
     {
         throw new Exception("panic.");
     }
     _origXml = xml;
     return((XmlDocument)xml?.CloneNode(true));
 }
Example #12
0
        public Station FromXML(string s)
        {
            // Create a document from the XML
            doc = new XmlDocument();
            doc.LoadXml(s);

            // Get the overall Station element
            XmlNode xmlNode = doc.CloneNode(true).FirstChild;

            // Station id
            int id = int.Parse(xmlNode.Attributes.GetNamedItem("id").Value);

            // Position
            int stationX = int.Parse(xmlNode.Attributes.GetNamedItem("X").Value);
            int stationY = int.Parse(xmlNode.Attributes.GetNamedItem("Y").Value);

            // Get first node (core)
            xmlNode = doc.CloneNode(true).FirstChild.FirstChild;
            int nid    = int.Parse(xmlNode.Attributes.GetNamedItem("id").Value);
            int health = int.Parse(xmlNode.Attributes.GetNamedItem("health").Value);

            // Set up core
            Node node = new Node(0, null);

            node.position = new Vector2(0, 0);
            node.data     = new StationNode(node, StationNodeType.Core, health);
            node.id       = nid;

            foreach (XmlNode child in xmlNode.ChildNodes)
            {
                RecursiveBuild(child, node);
            }

            // Create the station from preset tree
            Station fromXML = new Station(node, new Vector2(stationX, stationY));

            fromXML.id = id;

            SetStationRef(fromXML.station_tree, fromXML);

            return(fromXML);
        }
Example #13
0
        internal static XmlElement DefaultGetIdElement(XmlDocument document, string idValue)
        {
            if (document == null)
            {
                return(null);
            }

            try
            {
                XmlConvert.VerifyNCName(idValue);
            }
            catch (XmlException)
            {
                return(null);
            }

            XmlElement elem = document.GetElementById(idValue);

            if (elem != null)
            {
                XmlDocument docClone  = (XmlDocument)document.CloneNode(true);
                XmlElement  cloneElem = docClone.GetElementById(idValue);
                System.Diagnostics.Debug.Assert(cloneElem != null);

                if (cloneElem != null)
                {
                    cloneElem.Attributes.RemoveAll();

                    XmlElement cloneElem2 = docClone.GetElementById(idValue);

                    if (cloneElem2 != null)
                    {
                        throw new System.Security.Cryptography.CryptographicException(
                                  SR.Cryptography_Xml_InvalidReference);
                    }
                }

                return(elem);
            }

            elem = CheckSignatureManager.GetSingleReferenceTarget(document, "Id", idValue);
            if (elem != null)
            {
                return(elem);
            }
            elem = CheckSignatureManager.GetSingleReferenceTarget(document, "id", idValue);
            if (elem != null)
            {
                return(elem);
            }
            elem = CheckSignatureManager.GetSingleReferenceTarget(document, "ID", idValue);

            return(elem);
        }
Example #14
0
        public static void CloneComplexDocumentTrueAndManipulate()
        {
            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml("<a>test</a>");
            var cloned = xmlDocument.CloneNode(true);

            cloned.FirstChild.FirstChild.Value = "replaced";

            Assert.Equal("test", xmlDocument.FirstChild.FirstChild.Value);
            Assert.Equal("replaced", cloned.FirstChild.FirstChild.Value);
        }
 private XmlDocument Clone(XmlDocument xml)
 {
     if (Cloning != null)
     {
         Cloning();
     }
     if (_origXml != null)
     {
         throw new Exception("panic.");
     }
     _origXml = xml;
     return(xml == null ? null : (XmlDocument)xml.CloneNode(true));
 }
Example #16
0
        static private XmlDocument GenerateExtendPermitXml(XmlDocument currentPermit)
        {
            // The permit will be extended to reflect a customer extending their permit by 2 hours. The rate for the next 2 hours is $3
            // Update:
            //   - the expiry date (plus 2 hours)
            //   - total permit amount $5 (plus $3)
            //   - payment: new payment of $3

            XmlDocument updatePermit = (XmlDocument)currentPermit.CloneNode(true);

            foreach (XmlNode node in updatePermit.DocumentElement.ChildNodes)
            {
                switch (node.Name.ToLower())
                {
                case "permitnumber":
                case "purchaseddate":
                    // do nothing, required fields
                    break;

                case "expirydate":
                    // add 2 hours to the permit
                    node.InnerText = DateTime.ParseExact(node.InnerText, "yyyy-MM-ddTHH:mm:ss", null).AddHours(2).ToString("yyyy-MM-ddTHH:mm:ss");
                    break;

                case "permitamount":
                    // add $1 to the cost
                    node.InnerText = ((float.Parse(node.InnerText)) + 3.00).ToString();
                    break;

                case "payments":
                    node.AppendChild(node.ChildNodes[0].CloneNode(true));
                    // add a $1 card payment to the transaction
                    // Note: Create the new payment to relfect extension. It will create another payment entry in the system.
                    //       Refer to the API documentation for different payment examples.
                    node.ChildNodes[1].SelectSingleNode("Amount").InnerText = "3.00";
                    node.ChildNodes[1].SelectSingleNode("CardAuthorizationId").InnerText = "ghi789";
                    node.ChildNodes[1].SelectSingleNode("PaymentDate").InnerText         =
                        DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss");
                    break;

                default:
                    // remove all other tags (if supplied)
                    // currentPermit.DocumentElement.RemoveChild(node);
                    break;
                }
            }

            return(updatePermit);
        }
Example #17
0
        private void LoadXmlDocument()
        {
            Debug.Assert(_xpathDocument == null && _document == null && _xpathNavigator == null);

            if (!String.IsNullOrEmpty(_documentContent))
            {
                _document = XmlUtils.CreateXmlDocumentFromContent(_documentContent);
                return;
            }

            if (String.IsNullOrEmpty(_documentSource))
            {
                return;
            }

            // Make it absolute and check security
            string physicalPath = MapPathSecure(_documentSource);

            CacheStoreProvider cacheInternal = System.Web.HttpRuntime.Cache.InternalCache;
            string             key           = CacheInternal.PrefixLoadXml + physicalPath;

            _document = (XmlDocument)cacheInternal.Get(key);

            if (_document == null)
            {
                Debug.Trace("XmlControl", "XmlDocument not found in cache (" + _documentSource + ")");

                CacheDependency dependency;
                using (Stream stream = OpenFileAndGetDependency(null, physicalPath, out dependency)) {
                    _document = new XmlDocument();
                    _document.Load(XmlUtils.CreateXmlReader(stream, physicalPath));
                    cacheInternal.Insert(key, _document, new CacheInsertOptions()
                    {
                        Dependencies = dependency
                    });
                }
            }
            else
            {
                Debug.Trace("XmlControl", "XmlDocument found in cache (" + _documentSource + ")");
            }

            //
            lock (_document) {
                // Always return a clone of the cached copy
                _document = (XmlDocument)_document.CloneNode(true /*deep*/);
            }
        }
Example #18
0
 private void Form1_DragDrop(object sender, DragEventArgs e)
 {
     if (e.Data.GetDataPresent(DataFormats.FileDrop))
     {
         string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
         foreach (string s in files)
         {
             FileInfo    fI   = new FileInfo(s);
             XmlDocument temp = new XmlDocument();
             temp.LoadXml("<new><elements/></new>");
             activePanel         aP       = ((activePanel)sender);
             XmlNode             new_node = temp.CloneNode(false);
             ComponentCollection cc       = aP.Container.Components;
             aP.xml.InsertAfter(new_node, aP.xml.LastChild);
         }
     }
 }
Example #19
0
        /// <summary>
        /// Root of the preprocessing.
        /// </summary>
        private XmlDocument Preprocess()
        {
            XmlDocument outerDocument = _project.Xml.XmlDocument;

            XmlDocument destinationDocument = (XmlDocument)outerDocument.CloneNode(false /* shallow */);

            _filePaths.Push(_project.FullPath);

            if (!String.IsNullOrEmpty(_project.FullPath)) // Ignore in-memory projects
            {
                destinationDocument.AppendChild(destinationDocument.CreateComment("\r\n" + new String('=', 140) + "\r\n" + _project.FullPath + "\r\n" + new String('=', 140) + "\r\n"));
            }

            CloneChildrenResolvingImports(outerDocument, destinationDocument);

            return(destinationDocument);
        }
Example #20
0
        private void LoadXmlDocument()
        {
            Debug.Assert(_xpathDocument == null && _document == null);

            if (_documentContent != null && _documentContent.Length > 0)
            {
                _document = new XmlDocument();
                _document.LoadXml(_documentContent);
                return;
            }

            if (_documentSource == null || _documentSource.Length == 0)
            {
                return;
            }

            // Make it absolute and check security
            string physicalPath = MapPathSecure(_documentSource);

            CacheInternal cacheInternal = System.Web.HttpRuntime.CacheInternal;
            string        key           = "System.Web.UI.WebControls.LoadXmlDocument:" + physicalPath;

            _document = (XmlDocument)cacheInternal.Get(key);

            if (_document == null)
            {
                Debug.Trace("XmlControl", "XmlDocument not found in cache (" + _documentSource + ")");

                using (CacheDependency dependency = new CacheDependency(false, physicalPath)) {
                    _document = new XmlDocument();
                    _document.Load(physicalPath);
                    cacheInternal.UtcInsert(key, _document, dependency);
                }
            }
            else
            {
                Debug.Trace("XmlControl", "XmlDocument found in cache (" + _documentSource + ")");
            }

            // REVIEW: is this lock needed?  Maybe CloneNode is thread safe?
            lock (_document) {
                // Always return a clone of the cached copy
                _document = (XmlDocument)_document.CloneNode(true /*deep*/);
            }
        }
Example #21
0
        public static XmlDocument GetLocales(string formName, string lang = null)
        {
            var key = GetFormResourcesKey(formName, lang);

            if (_cache.ContainsKey(key))
            {
                return(_cache[key].CloneNode(true) as XmlDocument);
            }
            var doc = new XmlDocument();

            doc.LoadXml(GetResourceContents(key + "_res.xml"));
            if (lang != _defaultLang)
            {
                MergeWithDefaultResources(formName, doc);
            }
            if (!_cache.ContainsKey(key))
            {
                _cache.Add(key, doc);
            }
            return(doc.CloneNode(true) as XmlDocument);
        }
Example #22
0
        internal void AddRemoteConfig(XmlDocument remoteConfig)
        {
            if (remoteConfig != null && remoteConfig.InnerText != "")
            {
                // add RemoteConfiguration without the products list
                XmlDocument remoteConfigHeader = (XmlDocument)remoteConfig.CloneNode(true);
                remoteConfigHeader?.SelectSingleNode("//RemoteConfiguration")?.RemoveChild(remoteConfigHeader?.SelectSingleNode("//RemoteConfiguration/Products"));

                XmlParser.SetNode(xmlDoc, remoteConfigHeader.DocumentElement);
                XmlNodeList remoteProducts = remoteConfig.SelectNodes("//RemoteConfiguration/Products/Product");

                // add the products lists to Products
                if (remoteProducts.Count > 0)
                {
                    for (int i = (remoteProducts.Count - 1); i >= 0; i--)
                    {
                        XmlNode remoteProduct = remoteProducts[i];
                        XmlParser.SetNode(xmlDoc, xmlDoc.SelectSingleNode("//Products"), remoteProduct, false);
                    }
                }
            }
        }
Example #23
0
        /// <summary>
        /// Root of the preprocessing.
        /// </summary>
        private XmlDocument Preprocess()
        {
            XmlDocument outerDocument = _project.Xml.XmlDocument;

            int implicitImportCount = _project.Imports.Count(i => i.ImportingElement.ImplicitImportLocation != ImplicitImportLocation.None);
            // At the time of adding this feature, cloning is buggy.  The implicit imports are added to the XML document and removed after
            // processing.  This variable keeps track of the nodes that were added
            IList <XmlNode> addedNodes      = new List <XmlNode>(implicitImportCount);
            XmlElement      documentElement = outerDocument.DocumentElement;

            if (implicitImportCount > 0 && documentElement != null)
            {
                // Top implicit imports need to be added in the correct order by adding the first one at the top and each one after the first
                // one.  This variable keeps track of the last import that was added.
                XmlNode lastImplicitImportAdded = null;

                // Add the implicit top imports
                //
                foreach (var import in _project.Imports.Where(i => i.ImportingElement.ImplicitImportLocation == ImplicitImportLocation.Top))
                {
                    XmlNode node = outerDocument.ImportNode(import.ImportingElement.XmlElement, false);
                    if (lastImplicitImportAdded == null)
                    {
                        documentElement.InsertBefore(node, documentElement.FirstChild);
                        lastImplicitImportAdded = node;
                    }
                    else
                    {
                        documentElement.InsertAfter(node, lastImplicitImportAdded);
                    }
                    addedNodes.Add(node);
                }

                // Add the implicit bottom imports
                //
                foreach (var import in _project.Imports.Where(i => i.ImportingElement.ImplicitImportLocation == ImplicitImportLocation.Bottom))
                {
                    addedNodes.Add(documentElement.InsertAfter(outerDocument.ImportNode(import.ImportingElement.XmlElement, false), documentElement.LastChild));
                }
            }

            XmlDocument destinationDocument = (XmlDocument)outerDocument.CloneNode(false /* shallow */);

            _filePaths.Push(_project.FullPath);

            if (!String.IsNullOrEmpty(_project.FullPath)) // Ignore in-memory projects
            {
                destinationDocument.AppendChild(destinationDocument.CreateComment("\r\n" + new String('=', 140) + "\r\n" + _project.FullPath.Replace("--", "__") + "\r\n" + new String('=', 140) + "\r\n"));
            }

            CloneChildrenResolvingImports(outerDocument, destinationDocument);

            // Remove the nodes that were added as implicit imports
            //
            foreach (XmlNode addedNode in addedNodes)
            {
                documentElement?.RemoveChild(addedNode);
            }

            return(destinationDocument);
        }
Example #24
0
        internal void SplitOutProgramElements(string inputFileName, string outputFolder)
        {
            _logger.Info("Processing program elements started");

            using (var reader = XmlReader.Create(inputFileName))
            {
                if (reader.ReadToFollowing("root"))
                {
                    if (reader.ReadToDescendant("schedule"))
                    {
                        if (reader.ReadToDescendant("program"))
                        {
                            do
                            {
                                var element     = reader.ReadSubtree();
                                var programCode = GetProgramCode(ref element);

                                // First of all work pull out all the prescribing rules into
                                var prescribingRules = ExtractPrescribingRules(ref element)
                                                       .ToList();

                                if (prescribingRules.Count() >= 700)
                                {
                                    // There are two many prescribing-rules to write out to a single file

                                    // Create a version of the program without any prescribing-rule elements
                                    var programReader           = RemovePrescribingRulesFromProgram(element);
                                    var strippedProgramDocument = new XmlDocument();
                                    strippedProgramDocument.Load(programReader);

                                    const int passSize = 700;
                                    for (var pass = 0; pass *passSize < prescribingRules.Count; pass++)
                                    {
                                        var programDocument = (XmlDocument)strippedProgramDocument.CloneNode(true);
                                        var root            = programDocument.DocumentElement;

                                        var currentPass = prescribingRules
                                                          .Skip(pass * passSize)
                                                          .Take(passSize);

                                        foreach (var prescribingRule in currentPass)
                                        {
                                            var newElement = programDocument.CreateElement("prescribing-rule");
                                            newElement.InnerXml = prescribingRule.InnerXml;
                                            root?.InsertAfter(newElement, root.LastChild);
                                        }

                                        programDocument.Save(Path.Combine(outputFolder, "Program_" + programCode + "_" + (pass + 1) + ".xml"));
                                    }
                                }
                                else
                                {
                                    // The file is small enought that we can write it out verbatim
                                    WriteXmlToFile(Path.Combine(outputFolder, reader.Name + "_" + programCode + ".xml"), element);
                                }
                            } while (reader.ReadToNextSibling("program"));
                        }
                    }
                }
            }

            _logger.Info("Processing program elements completed");
        }
Example #25
0
        internal static XmlElement DefaultGetIdElement(XmlDocument document, string idValue)
        {
            if (document == null)
            {
                return(null);
            }

            try
            {
                XmlConvert.VerifyNCName(idValue);
            }
            catch (XmlException)
            {
                // Identifiers are required to be an NCName
                //   (xml:id version 1.0, part 4, paragraph 2, bullet 1)
                //
                // If it isn't an NCName, it isn't allowed to match.
                return(null);
            }

            // Get the element with idValue
            XmlElement elem = document.GetElementById(idValue);

            if (elem != null)
            {
                // Have to check for duplicate ID values from the DTD.

                XmlDocument docClone  = (XmlDocument)document.CloneNode(true);
                XmlElement  cloneElem = docClone.GetElementById(idValue);

                // If it's null here we want to know about it, because it means that
                // GetElementById failed to work across the cloning, and our uniqueness
                // test is invalid.
                System.Diagnostics.Debug.Assert(cloneElem != null);

                // Guard against null anyways
                if (cloneElem != null)
                {
                    cloneElem.Attributes.RemoveAll();

                    XmlElement cloneElem2 = docClone.GetElementById(idValue);

                    if (cloneElem2 != null)
                    {
                        throw new CryptographicException(
                                  SR.Cryptography_Xml_InvalidReference);
                    }
                }

                return(elem);
            }

            elem = GetSingleReferenceTarget(document, "Id", idValue);
            if (elem != null)
            {
                return(elem);
            }
            elem = GetSingleReferenceTarget(document, "id", idValue);
            if (elem != null)
            {
                return(elem);
            }
            elem = GetSingleReferenceTarget(document, "ID", idValue);

            return(elem);
        }
Example #26
0
 protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
 {
     original = new XmlDocument().ReadNode(reader);
     node     = original.CloneNode(true);
 }
Example #27
0
        public static void CloneComplexDocumentTrueAndManipulate()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<a>test</a>");
            var cloned = xmlDocument.CloneNode(true);

            cloned.FirstChild.FirstChild.Value = "replaced";

            Assert.Equal("test", xmlDocument.FirstChild.FirstChild.Value);
            Assert.Equal("replaced", cloned.FirstChild.FirstChild.Value);
        }
Example #28
0
        public string XPathQuery()
        {
            XmlDocument resultDocument = (XmlDocument)_domDataBase.CloneNode(true), tempDocument = (XmlDocument)_domDataBase.CloneNode(true);
            XmlNodeList resultNodes;

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[contains(title, '" + _title + "')]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film['" + _genre + "'='' or ./genre[child::text()='" + _genre + "']]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[" + _fromYear + "=-1 or (year>=" + _fromYear + " and year<=" + _toYear + ")]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film['" + _country + "'='' or ./country[child::text()='" + _country + "']]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[./director[contains(., '" + _director + "')]]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[./character[contains(., '" + _actor + "')]]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[" + _imdbRate + "=-1 or rate[@IMDB>=" + _imdbRate + "]]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[" + Convert.ToDouble(_kinopoiskRate).ToString("G", CultureInfo.InvariantCulture) + "=-1 or rate[@kinopoisk>=" + (Convert.ToDouble(_kinopoiskRate) - 1e-6).ToString("G", CultureInfo.InvariantCulture) + "]]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[" + _length + "=-1 or length>=" + _length + "]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            resultNodes = resultDocument.SelectNodes("/mediaDatabase/film[contains(anotation, '" + _anotation + "')]");
            tempDocument.SelectSingleNode("mediaDatabase").RemoveAll();
            foreach (XmlNode item in resultNodes)
            {
                tempDocument.SelectSingleNode("mediaDatabase").AppendChild(tempDocument.ImportNode(item, true));
            }
            resultDocument = (XmlDocument)tempDocument.CloneNode(true);

            var resultString = new StringBuilder();

            resultString.AppendLine("Кількість результатів: " +
                                    resultDocument.SelectSingleNode("mediaDatabase").ChildNodes.Count + "\n");
            foreach (XmlNode item in resultDocument.SelectSingleNode("mediaDatabase").ChildNodes)
            {
                resultString.AppendLine("Назва: " + item.SelectSingleNode("title").FirstChild.Value);
                for (int i = 0; i < item.SelectNodes("genre").Count; i++)
                {
                    if (i == 0)
                    {
                        resultString.Append("Жанри: " + item.SelectNodes("genre")[i].FirstChild.Value);
                    }
                    else
                    {
                        resultString.Append(", " + item.SelectNodes("genre")[i].FirstChild.Value);
                    }
                }
                resultString.AppendLine();
                resultString.AppendLine("Рік: " + item.SelectSingleNode("year").FirstChild.Value);
                for (int i = 0; i < item.SelectNodes("country").Count; i++)
                {
                    if (i == 0)
                    {
                        resultString.Append("Країни: " + item.SelectNodes("country")[i].FirstChild.Value);
                    }
                    else
                    {
                        resultString.Append(", " + item.SelectNodes("country")[i].FirstChild.Value);
                    }
                }
                resultString.AppendLine();
                for (int i = 0; i < item.SelectNodes("director").Count; i++)
                {
                    if (i == 0)
                    {
                        resultString.Append("Режисери: " + item.SelectNodes("director")[i].FirstChild.Value);
                    }
                    else
                    {
                        resultString.Append(", " + item.SelectNodes("director")[i].FirstChild.Value);
                    }
                }
                resultString.AppendLine();
                for (int i = 0; i < item.SelectNodes("character").Count; i++)
                {
                    if (i == 0)
                    {
                        resultString.Append("Актори: " + item.SelectNodes("character")[i].FirstChild.Value);
                    }
                    else
                    {
                        resultString.Append(", " + item.SelectNodes("character")[i].FirstChild.Value);
                    }
                }
                resultString.AppendLine();
                resultString.AppendLine("Рейтинг IMDB: " + item.SelectSingleNode("rate").Attributes["IMDB"].Value);
                resultString.AppendLine("Рейтинг Кінопошуку: " + item.SelectSingleNode("rate").Attributes["kinopoisk"].Value);
                resultString.AppendLine("Час: " + item.SelectSingleNode("length").FirstChild.Value + " хв");
                resultString.AppendLine("Анотація:\n" + item.SelectSingleNode("anotation").FirstChild.Value);
                resultString.AppendLine();
            }
            return(resultString.ToString());
        }