Пример #1
0
        public static void DocumentElementNodeWithNewNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<root/>");

            var root = xmlDocument.DocumentElement;
            var newRoot = xmlDocument.CreateElement("newroot");

            xmlDocument.ReplaceChild(newRoot, root);
            Assert.Same(newRoot, xmlDocument.DocumentElement);
        }
Пример #2
0
        public void SaveToXml(XmlDocument xmlDoc, XmlNode XMLNode, string sXMLEncoding, Selection Selection_Collection, string nspace)
        {
            NodesList list;
            XmlNode targetXmlNode = null;
            XmlNode selNode = null;
            bool ownSel = false;
            if ((Selection_Collection != null) && (this == Selection_Collection.parent))
            {
                ownSel = true;
                targetXmlNode = XMLNode;
            }
            
            if (type_ == null)
            {
                return;
            }

            if (!ownSel)
            {
                if (type_.type == ElementType.Entity)
                {
                    targetXmlNode = xmlDoc.CreateNode(XmlNodeType.EntityReference, xmlTagName, nspace);
                }
                else if ((type_.xmlTag != null) && (type_.xmlTag.Length > 0))
                {
                    {
                        targetXmlNode = xmlDoc.CreateNode(XmlNodeType.Element, type_.xmlTag, nspace);

                        if (((type_.type == ElementType.Ms) ||
                             (type_.type == ElementType.Mtext)) &&
                            (((targetXmlNode != null) && (literalText != null)) && (literalText.Length > 0)))
                        {
                            string s = literalText;
                            if (Selection_Collection != null)
                            {
                                if ((Selection_Collection.First != null) && (Selection_Collection.First == this))
                                {
                                    if ((Selection_Collection.Last != null) && (Selection_Collection.Last == this))
                                    {
                                        s = s.Substring(Selection_Collection.caret,
                                                            Selection_Collection.literalLength -
                                                            Selection_Collection.caret);
                                    }
                                    else
                                    {
                                        s = s.Substring(Selection_Collection.caret,
                                                            s.Length - Selection_Collection.caret);
                                    }
                                }
                                else if (((Selection_Collection.Last != null) && (Selection_Collection.Last == this)) &&
                                         (Selection_Collection.First != this))
                                {
                                    s = s.Substring(0, Selection_Collection.literalLength);
                                }
                            }
                            selNode = xmlDoc.CreateTextNode(s);
                            targetXmlNode.AppendChild(selNode);
                        }
                        else if (((type_.type != ElementType.Mglyph) && (targetXmlNode != null)) &&
                                 ((literalText != null) && (literalText.Length > 0)))
                        {
                            string s = literalText;
                            if (Selection_Collection != null)
                            {
                                if ((Selection_Collection.First != null) && (Selection_Collection.First == this))
                                {
                                    if ((Selection_Collection.Last != null) && (Selection_Collection.Last == this))
                                    {
                                        s =
                                            s.Substring(Selection_Collection.caret,
                                                            Selection_Collection.literalLength -
                                                            Selection_Collection.caret);
                                    }
                                    else
                                    {
                                        s =
                                            s.Substring(Selection_Collection.caret,
                                                            s.Length - Selection_Collection.caret);
                                    }
                                }
                                else if (((Selection_Collection.Last != null) && (Selection_Collection.Last == this)) &&
                                         (Selection_Collection.First != this))
                                {
                                    s = s.Substring(0, Selection_Collection.literalLength);
                                }
                            }
                            selNode = xmlDoc.CreateTextNode(s);
                            targetXmlNode.AppendChild(selNode);
                        }
                    }
                }
            }
            if (targetXmlNode == null)
            {
                return;
            }
            
            if (XMLNode == null)
            {
                string xml = "";
                if (sXMLEncoding == "UTF-16")
                {
                    xml = "<?xml version='1.0' encoding='UTF-16'?>";
                }
                else if (sXMLEncoding == "UTF-8")
                {
                    xml = "<?xml version='1.0' encoding='UTF-8'?>";
                }
                else if (sXMLEncoding.Length > 0)
                {
                    xml = "<?xml version='1.0' encoding='" + sXMLEncoding + "'?>";
                }
                else
                {
                    xml = "<?xml version='1.0'?>";
                }
                xml = xml + "<root/>";
                xmlDoc.LoadXml(xml);
                if ((type_.type == ElementType.Math) && displayStyle)
                {
                    XmlAttribute attribute = xmlDoc.CreateAttribute("", "display", "");
                    attribute.Value = "block";
                    targetXmlNode.Attributes.Append(attribute);
                }
                
                xmlDoc.ReplaceChild(targetXmlNode, xmlDoc.DocumentElement);
            }
            else if ((!ownSel && !false) && !false)
            {
                {
                    XMLNode.AppendChild(targetXmlNode);
                }
                if ((type_.type == ElementType.Math) && displayStyle)
                {
                    XmlAttribute attribute = xmlDoc.CreateAttribute("", "display", "");
                    attribute.Value = "block";
                    targetXmlNode.Attributes.Append(attribute);
                    XMLNode.AppendChild(targetXmlNode);
                }
            }
            if (((((Selection_Collection == null) || (this != Selection_Collection.parent)))) && ((!HasChildren())))
            {
                return;
            }
            if ((Selection_Collection != null) && (this == Selection_Collection.parent))
            {
                list = Selection_Collection.nodesList;
            }
            else
            {
                list = GetChildrenNodes();
            }
            
            list.Reset();
            Node next = list.Next();
            int level = 0;
            bool sameSel = false;
            bool isPrev = false;
            bool isNext = false;
            XmlNode curXmlNode = targetXmlNode;
            bool ok = true;
            while ((next != null) && ok)
            {
                sameSel = false;
                isPrev = false;
                isNext = false;

                if (next.type_.type != ElementType.Entity)
                {
                    if ((Selection_Collection != null) && (next == Selection_Collection.First))
                    {
                        if (next.IsSameStyleParent())
                        {
                            sameSel = true;
                        }
                    }
                    else if (next.prevSibling == null)
                    {
                        if (next.IsSameStyleParent())
                        {
                            sameSel = true;
                        }
                    }
                    else if (!next.IsSameStyle(next.prevSibling))
                    {
                        if (next.IsSameStyleParent() && next.prevSibling.IsSameStyleParent())
                        {
                            isNext = true;
                        }
                        else
                        {
                            if (next.prevSibling.IsSameStyleParent())
                            {
                                isPrev = true;
                            }
                            if (next.IsSameStyleParent())
                            {
                                sameSel = true;
                            }
                        }
                    }
                }
                if (isNext)
                {
                    if (next.prevSibling.IsSameStyleParent() && (level > 0))
                    {
                        curXmlNode = curXmlNode.ParentNode;
                        level--;
                    }
                    sameSel = true;
                }
                if (sameSel && next.IsSameStyleParent())
                {
                    Node snode;
                    if (next.style_ == null)
                    {
                        snode = new Node();
                        next.style_ = new StyleAttributes();
                    }
                    if ((next.parent_ != null) && (next.parent_.style_ != null))
                    {
                        snode = new Node(next.parent_.style_);
                    }
                    else
                    {
                        snode = new Node(new StyleAttributes());
                    }
                    XmlNode mstyleNode = null;
                    mstyleNode = xmlDoc.CreateNode(XmlNodeType.Element, "mstyle", nspace);
                    AttributeBuilder.CascadeStyles(next.parent_, snode, next.style_);
                    if (snode.attrs != null)
                    {
                        snode.attrs.Reset();
                        for (Attribute i = snode.attrs.Next(); i != null; i = snode.attrs.Next())
                        {
                            XmlAttribute attr = xmlDoc.CreateAttribute("", i.name, "");
                            attr.Value = i.val;
                            mstyleNode.Attributes.Append(attr);
                        }
                        snode.attrs.Reset();
                    }
                    curXmlNode.AppendChild(mstyleNode);
                    curXmlNode = mstyleNode;
                    level++;
                }
                if (isPrev && next.prevSibling.IsSameStyleParent())
                {
                    curXmlNode = curXmlNode.ParentNode;
                    level--;
                }

                next.SaveToXml(xmlDoc, curXmlNode, sXMLEncoding, Selection_Collection, nspace);
                next = list.Next();
                if (((Selection_Collection != null) && (Selection_Collection.Last != null)) &&
                    ((next == Selection_Collection.Last) && (Selection_Collection.literalLength == 0)))
                {
                    ok = false;
                }
            }
        }
Пример #3
0
 private void updateElementName(XmlDocument doc, String oldName, String newName)
 {
     XmlElement oldElement = (XmlElement)doc.GetElementsByTagName(oldName)[0];
     XmlElement newElement = copyElementToName(oldElement, newName);
     doc.ReplaceChild(newElement,oldElement);
 }
Пример #4
0
        /// <inheritdoc />
        public override void Apply(XmlDocument document, string key)
        {
            // Set the evaluation context
            context["key"] = key;

            XPathExpression xpath = pathExpression.Clone();
            xpath.SetContext(context);

            // Evaluate the path
            string path = document.CreateNavigator().Evaluate(xpath).ToString();

            if(basePath != null)
                path = Path.Combine(basePath, path);

            string targetDirectory = Path.GetDirectoryName(path);

            if(!Directory.Exists(targetDirectory))
                Directory.CreateDirectory(targetDirectory);

            if(writeXhtmlNamespace)
            {
                document.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/1999/xhtml");
                document.LoadXml(document.OuterXml);
            }

            if (settings.OutputMethod == XmlOutputMethod.Html)
            {
                XmlDocumentType documentType = document.CreateDocumentType("html", null, null, null);
                if (document.DocumentType != null)
                {
                    document.ReplaceChild(documentType, document.DocumentType);
                }
                else
                {
                    document.InsertBefore(documentType, document.FirstChild);
                }
            }

            // Save the document.

            // selectExpression determines which nodes get saved. If there is no selectExpression we simply
            // save the root node as before. If there is a selectExpression, we evaluate the XPath expression
            // and save the resulting node set. The select expression also enables the "literal-text" processing
            // instruction, which outputs its content as unescaped text.
            if(selectExpression == null)
            {
                try
                {
                    using(XmlWriter writer = XmlWriter.Create(path, settings))
                    {
                        document.Save(writer);
                    }
                }
                catch(IOException e)
                {
                    base.WriteMessage(key, MessageLevel.Error, "An access error occurred while attempting to " +
                        "save to the file '{0}'. The error message is: {1}", path, e.GetExceptionMessage());
                }
                catch(XmlException e)
                {
                    base.WriteMessage(key, MessageLevel.Error, "Invalid XML was written to the output " +
                        "file '{0}'. The error message is: '{1}'", path, e.GetExceptionMessage());
                }
            }
            else
            {
                // IMPLEMENTATION NOTE: The separate StreamWriter is used to maintain XML indenting.  Without it
                // the XmlWriter won't honor our indent settings after plain text nodes have been written.
                using(StreamWriter output = File.CreateText(path))
                {
                    using(XmlWriter writer = XmlWriter.Create(output, settings))
                    {
                        XPathExpression select_xpath = selectExpression.Clone();
                        select_xpath.SetContext(context);

                        XPathNodeIterator ni = document.CreateNavigator().Select(selectExpression);

                        while(ni.MoveNext())
                        {
                            if(ni.Current.NodeType == XPathNodeType.ProcessingInstruction &&
                              ni.Current.Name.Equals("literal-text"))
                            {
                                writer.Flush();
                                output.Write(ni.Current.Value);
                            }
                            else
                                ni.Current.WriteSubtree(writer);
                        }
                    }
                }
            }

            // Raise an event to indicate that a file was created
            this.OnComponentEvent(new FileCreatedEventArgs(path, true));
        }
Пример #5
0
 public void UpdateElementName(XmlDocument doc, string oldName, string newName)
 {
     var itemOf = (XmlElement)doc.GetElementsByTagName(oldName)[0];
     var name = CopyElementToName(itemOf, newName);
     doc.ReplaceChild(name, itemOf);
 }
        public XmlDocument SerializeGovTalkMessage()
        {
            _loggingService.LogInfo(this, "Serializing GovTalkMessage.");

            using(MemoryStream memStream = new MemoryStream())
            {
                XmlWriterSettings settings = new XmlWriterSettings
                {
                    Indent = true,
                    IndentChars = "\t",
                    Encoding = Encoding.UTF8
                };

                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, "http://www.govtalk.gov.uk/CM/envelope");

                XmlSerializer serializer = new XmlSerializer(typeof(GovTalkMessage));
                serializer.Serialize(XmlWriter.Create(memStream,settings), _govTalkMessageBuilder.GovTalkMessage, ns);

                memStream.Seek(0, SeekOrigin.Begin);

                // Use XmlWriter to make use of settings
                // Load to XmlDoc for ease of use by client

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(memStream);

                XmlDeclaration xmlDeclaration;
                xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

                doc.ReplaceChild(xmlDeclaration, doc.FirstChild);

                return doc;
            }
        }
Пример #7
0
                public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
                {
                    string local_path = absoluteUri.LocalPath;
                    bool root_xsl = local_path.Equals (local_path, StringComparison.CurrentCultureIgnoreCase);

                    XmlDocument doc = new XmlDocument ();
                    doc.Load (local_path);
                    if (_files != null)
                        _files.Add (local_path);

                    XmlNodeList list = doc.DocumentElement.GetElementsByTagName ("output", NS_XSL);
                    for (int i = 0; i < list.Count; i++)
                        doc.DocumentElement.RemoveChild (list[i]);

                    if (!_html4) {
                        if (root_xsl) {
                            SetupXSLOutput (doc, "xml", "utf-8", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd", _indent);
                        }
                    } else {
                        XmlElement new_root = ConvertXHTMLtoHTML (doc, doc.DocumentElement);
                        doc.ReplaceChild (new_root, doc.DocumentElement);
                        if (root_xsl) {
                            SetupXSLOutput (doc, "html", "utf-8", "-//W3C//DTD HTML 4.01//EN", "http://www.w3.org/TR/html4/strict.dtd", _indent);
                        }
                    }

                    using (MemoryStream ms = new MemoryStream ())
                    using (XmlTextWriter writer = new XmlTextWriter (ms, System.Text.Encoding.UTF8)) {
                        doc.WriteTo (writer);
                        writer.Close ();
                        ms.Close ();
                        return new MemoryStream (ms.ToArray ());
                    }
                }
Пример #8
0
        public static void ReplaceNodeWithChildrenWithEmptyNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<root><child1/><child2/></root>");

            var newNode = xmlDocument.CreateElement("newElement");

            Assert.True(xmlDocument.DocumentElement.HasChildNodes);
            xmlDocument.ReplaceChild(newNode, xmlDocument.DocumentElement);
            Assert.False(xmlDocument.DocumentElement.HasChildNodes);
        }