예제 #1
0
        // Writes the content (inner XML) of the current node into the provided XmlTextWriter.
        private async Task WriteNodeAsync(XmlTextWriter xtw, bool defattr)
        {
            int d = NodeType == XmlNodeType.None ? -1 : Depth;

            while (await ReadAsync().ConfigureAwait(false) && d < Depth)
            {
                switch (NodeType)
                {
                case XmlNodeType.Element:
                    xtw.WriteStartElement(Prefix, LocalName, NamespaceURI);
                    xtw.QuoteChar = QuoteChar;
                    xtw.WriteAttributes(this, defattr);
                    if (IsEmptyElement)
                    {
                        xtw.WriteEndElement();
                    }
                    break;

                case XmlNodeType.Text:
                    xtw.WriteString(await GetValueAsync().ConfigureAwait(false));
                    break;

                case XmlNodeType.Whitespace:
                case XmlNodeType.SignificantWhitespace:
                    xtw.WriteWhitespace(await GetValueAsync().ConfigureAwait(false));
                    break;

                case XmlNodeType.CDATA:
                    xtw.WriteCData(Value);
                    break;

                case XmlNodeType.EntityReference:
                    xtw.WriteEntityRef(Name);
                    break;

                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    xtw.WriteProcessingInstruction(Name, Value);
                    break;

                case XmlNodeType.DocumentType:
                    xtw.WriteDocType(Name, GetAttribute("PUBLIC"), GetAttribute("SYSTEM"), Value);
                    break;

                case XmlNodeType.Comment:
                    xtw.WriteComment(Value);
                    break;

                case XmlNodeType.EndElement:
                    xtw.WriteFullEndElement();
                    break;
                }
            }
            if (d == Depth && NodeType == XmlNodeType.EndElement)
            {
                await ReadAsync().ConfigureAwait(false);
            }
        }
예제 #2
0
        private void WriteNode(XmlTextWriter xtw, bool defattr)
        {
            int d = this.NodeType == XmlNodeType.None ? -1 : this.Depth;

            while (this.Read() && (d < this.Depth))
            {
                switch (this.NodeType)
                {
                case XmlNodeType.Element:
                    xtw.WriteStartElement(this.Prefix, this.LocalName, this.NamespaceURI);
                    xtw.QuoteChar = this.QuoteChar;
                    xtw.WriteAttributes(this, defattr);
                    if (this.IsEmptyElement)
                    {
                        xtw.WriteEndElement();
                    }
                    break;

                case XmlNodeType.Text:
                    xtw.WriteString(this.Value);
                    break;

                case XmlNodeType.Whitespace:
                case XmlNodeType.SignificantWhitespace:
                    xtw.WriteWhitespace(this.Value);
                    break;

                case XmlNodeType.CDATA:
                    xtw.WriteCData(this.Value);
                    break;

                case XmlNodeType.EntityReference:
                    xtw.WriteEntityRef(this.Name);
                    break;

                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    xtw.WriteProcessingInstruction(this.Name, this.Value);
                    break;

                case XmlNodeType.DocumentType:
                    xtw.WriteDocType(this.Name, this.GetAttribute("PUBLIC"), this.GetAttribute("SYSTEM"), this.Value);
                    break;

                case XmlNodeType.Comment:
                    xtw.WriteComment(this.Value);
                    break;

                case XmlNodeType.EndElement:
                    xtw.WriteFullEndElement();
                    break;
                }
            }
            if (d == this.Depth && this.NodeType == XmlNodeType.EndElement)
            {
                Read();
            }
        }
예제 #3
0
        static void Main(string[] args)
        {
            XmlTextReader Reader = new XmlTextReader(@"..\..\..\Data\Users.xml");
            XmlTextWriter Writer = new XmlTextWriter(@"..\..\..\Data\Users2.xml", null);

            Writer.Formatting = Formatting.Indented;

            while (Reader.Read())
            {
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "User"))
                {
                    Writer.WriteStartElement(Reader.Name);
                    Reader.MoveToNextAttribute();
                    Writer.WriteAttributeString("ID", "User" + Reader.Value);
                    Reader.MoveToNextAttribute();
                    Writer.WriteAttributeString("UserName", Reader.Value);
                }
                else
                {
                    switch (Reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        Writer.WriteStartElement(Reader.Name);
                        Writer.WriteAttributes(Reader, false);
                        break;

                    case XmlNodeType.CDATA:
                        Writer.WriteCData(Reader.Value);
                        break;

                    case XmlNodeType.EndElement:
                        Writer.WriteEndElement();
                        break;

                    case XmlNodeType.EntityReference:
                        Writer.WriteEntityRef(Reader.Name);
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        Writer.WriteProcessingInstruction(Reader.Name, Reader.Value);
                        break;

                    case XmlNodeType.Text:
                    case XmlNodeType.SignificantWhitespace:
                        Writer.WriteString(Reader.Value);
                        break;

                    default:
                        break;
                    }
                }
            }
            Reader.Close();
            Writer.Close();
        }
예제 #4
0
        public static void Test()
        {
            XmlTextWriter writer = null;

            writer = new XmlTextWriter(filename, null);
            //为使文件易读,使用缩进
            writer.Formatting = Formatting.Indented;
            //写XML声明
            writer.WriteStartDocument();

            //引用样式
            String PItext = "type='text/xsl' href='book.xsl'";

            writer.WriteProcessingInstruction("xml-stylesheet", PItext);
            //文档类型
            writer.WriteDocType("book", null, null, "<!ENTITY h 'hardcover'>");
            //写入注释
            writer.WriteComment("sample XML");

            //写一个元素(根元素)
            writer.WriteStartElement("book");
            //属性
            writer.WriteAttributeString("genre", "novel");
            writer.WriteAttributeString("ISBN", "1-8630-014");

            //书名元素
            writer.WriteElementString("title", "The Handmaid's Tale");
            //Write the style element
            writer.WriteStartElement("style");
            writer.WriteEntityRef("h");
            writer.WriteEndElement();
            //价格元素
            writer.WriteElementString("price", "19.95");
            //写入 CDATA
            writer.WriteCData("Prices 15% off!!");
            //关闭根元素
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();

            //加载文件
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.Load(filename);
            //XML文件的内容显示在控制台
            Console.Write(doc.InnerXml);
        }
예제 #5
0
        private void  WriteAttributeValue(XmlTextWriter xtw)
        {
            String attrName = this.Name;

            while (ReadAttributeValue())
            {
                if (this.NodeType == XmlNodeType.EntityReference)
                {
                    xtw.WriteEntityRef(this.Name);
                }
                else
                {
                    xtw.WriteString(this.Value);
                }
            }
            this.MoveToAttribute(attrName);
        }
예제 #6
0
 static void CreateXML()
 {
     try
     {
         using (var writer = new XmlTextWriter("students.xml", Encoding.UTF8))
         {
             writer.Formatting = Formatting.Indented;
             writer.WriteStartDocument();
             {
                 writer.WriteDocType("students", null, null, "<!ENTITY hello \"Привіт, \">");
                 writer.WriteStartElement("students");
                 {
                     writer.WriteComment("test comment");
                     writer.WriteStartElement("student");
                     {
                         writer.WriteStartElement("pib");
                         {
                             writer.WriteEntityRef("hello");
                             writer.WriteString("Іваненко Іван Іванович");
                         }
                         writer.WriteEndElement();
                         writer.WriteElementString("bday", "02.05.1996");
                         writer.WriteElementString("avg", "10,99");
                         writer.WriteStartElement("address");
                         {
                             writer.WriteAttributeString("region", "Житомирська обл.");
                             writer.WriteAttributeString("country", "Україна");
                             writer.WriteString("Житомир");
                         }
                     }
                     writer.WriteEndElement();
                 }
                 writer.WriteEndElement();
             }
             writer.WriteEndDocument();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
예제 #7
0
    public static void Main()
    {
        XmlTextWriter writer = null;

        writer = new XmlTextWriter(filename, null);
        //Use indenting for readability.
        writer.Formatting = Formatting.Indented;

        //Write the XML delcaration
        writer.WriteStartDocument();

        //Write the ProcessingInstruction node.
        String PItext = "type=\"text/xsl\" href=\"book.xsl\"";

        writer.WriteProcessingInstruction("xml-stylesheet", PItext);

        //Write the DocumentType node.
        writer.WriteDocType("book", null, null, "<!ENTITY h \"hardcover\">");

        //Write a Comment node.
        writer.WriteComment("sample XML");

        //Write the root element.
        writer.WriteStartElement("book");

        //Write the genre attribute.
        writer.WriteAttributeString("genre", "novel");

        //Write the ISBN attribute.
        writer.WriteAttributeString("ISBN", "1-8630-014");

        //Write the title.
        writer.WriteElementString("title", "The Handmaid's Tale");

        //Write the style element.
        writer.WriteStartElement("style");
        writer.WriteEntityRef("h");
        writer.WriteEndElement();

        //Write the price.
        writer.WriteElementString("price", "19.95");

        //Write CDATA.
        writer.WriteCData("Prices 15% off!!");

        //Write the close tag for the root element.
        writer.WriteEndElement();

        writer.WriteEndDocument();

        //Write the XML to file and close the writer.
        writer.Flush();
        writer.Close();

        //Load the file into an XmlDocument to ensure well formed XML.
        XmlDocument doc = new XmlDocument();

        //Preserve white space for readability.
        doc.PreserveWhitespace = true;
        //Load the file.
        doc.Load(filename);

        //Display the XML content to the console.
        Console.Write(doc.InnerXml);
    }
예제 #8
0
        internal bool ParseReaderNode()
        {
            if (reader.Depth > markupDepth)
            {
                if (writer != null)   // ProcessMarkup
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
                        writer.WriteAttributes(reader, false);
                        if (reader.IsEmptyElement)
                        {
                            writer.WriteEndElement();
                        }
                        break;

                    case XmlNodeType.Text:
                        writer.WriteString(reader.Value);
                        break;

                    case XmlNodeType.SignificantWhitespace:
                        writer.WriteWhitespace(reader.Value);
                        break;

                    case XmlNodeType.CDATA:
                        writer.WriteCData(reader.Value);
                        break;

                    case XmlNodeType.EntityReference:
                        writer.WriteEntityRef(reader.Name);
                        break;

                    case XmlNodeType.Comment:
                        writer.WriteComment(reader.Value);
                        break;

                    case XmlNodeType.EndElement:
                        writer.WriteFullEndElement();
                        break;
                    }
                }
                return(true);
            }
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (builder.ProcessElement(reader.Prefix, reader.LocalName, reader.NamespaceURI))
                {
                    namespaceManager.PushScope();
                    if (reader.MoveToFirstAttribute())
                    {
                        do
                        {
                            builder.ProcessAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI, reader.Value);
                            if (Ref.Equal(reader.NamespaceURI, schemaNames.NsXmlNs) && isProcessNamespaces)
                            {
                                namespaceManager.AddNamespace(reader.Prefix == string.Empty ? string.Empty : reader.LocalName, reader.Value);
                            }
                        }while (reader.MoveToNextAttribute());
                        reader.MoveToElement(); // get back to the element
                    }
                    builder.StartChildren();
                    if (reader.IsEmptyElement)
                    {
                        namespaceManager.PopScope();
                        builder.EndChildren();
                    }
                    else if (!builder.IsContentParsed())
                    {
                        markupDepth  = reader.Depth;
                        stringWriter = new StringWriter();
                        writer       = new XmlTextWriter(stringWriter);
                        writer.WriteStartElement(reader.LocalName);
                    }
                }
                else if (!reader.IsEmptyElement)
                {
                    markupDepth = reader.Depth;
                    writer      = null;
                }
            }
            else if (reader.NodeType == XmlNodeType.Text ||
                     reader.NodeType == XmlNodeType.EntityReference ||
                     reader.NodeType == XmlNodeType.SignificantWhitespace ||
                     reader.NodeType == XmlNodeType.CDATA)
            {
                builder.ProcessCData(reader.Value);
            }
            else if (reader.NodeType == XmlNodeType.EndElement)
            {
                if (reader.Depth == markupDepth)
                {
                    if (writer != null)   // processUnparsedContent
                    {
                        writer.WriteEndElement();
                        writer.Close();
                        writer = null;
                        XmlDocument doc = new XmlDocument();
                        doc.Load(new XmlTextReader(new StringReader(stringWriter.ToString())));
                        XmlNodeList list   = doc.DocumentElement.ChildNodes;
                        XmlNode[]   markup = new XmlNode[list.Count];
                        for (int i = 0; i < list.Count; i++)
                        {
                            markup[i] = list[i];
                        }
                        builder.ProcessMarkup(markup);
                        namespaceManager.PopScope();
                        builder.EndChildren();
                    }
                    markupDepth = int.MaxValue;
                }
                else
                {
                    namespaceManager.PopScope();
                    builder.EndChildren();
                }
                if (reader.Depth == schemaXmlDepth)
                {
                    return(false); // done
                }
            }
            return(true);
        }
예제 #9
0
        /// <summary>
        /// Copies everything from the reader object to the writer instance
        /// </summary>
        /// <param name="writer">The XmlTextWriter to copy to.</param>
        /// <param name="reader">The XmlReader to read from.</param>
        /// <param name="defattr">true to copy the default attributes from the XmlReader; otherwise, false.</param>
        /// <param name="skipHtmlNode">是否跳过html节点</param>
        /// <param name="clearTag">是否清除html tag,只输出纯文本</param>
        /// <param name="maxCount">copy的文本的字符数,如果maxCount&lt;=0,copy全部文本</param>
        /// <param name="endStr">如果只copy了部分文本,部分文本后的附加字符,如...</param>
        public static void WriteXml(XmlTextWriter writer, XmlReader reader, bool defattr, bool skipHtmlNode, bool clearTag, int maxCount, string endStr)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            int  count    = 0;
            bool finished = false;

            reader.Read();
            while (!finished && !reader.EOF)
            {
                char[] writeNodeBuffer   = null;
                bool   canReadValueChunk = reader.CanReadValueChunk;
                int    num = (reader.NodeType == XmlNodeType.None) ? -1 : reader.Depth;
                do
                {
                    if (clearTag && reader.NodeType != XmlNodeType.Text)
                    {
                        writer.WriteString(" ");
                        continue;
                    }
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        if (skipHtmlNode && reader.Name != null && reader.Name.ToLower() == "html")
                        {
                            break;
                        }
                        writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
                        writer.WriteAttributes(reader, defattr);
                        if (reader.IsEmptyElement)
                        {
                            writer.WriteEndElement();
                        }
                        break;

                    case XmlNodeType.Text:
                        int num2;
                        if (!canReadValueChunk)
                        {
                            if (maxCount > 0)
                            {
                                string value = reader.Value;
                                if ((count + value.Length) >= maxCount)
                                {
                                    value = value.Substring(0, (maxCount - count));
                                    if (!String.IsNullOrEmpty(endStr))
                                    {
                                        value += endStr;
                                    }
                                    finished = true;
                                }
                                writer.WriteString(value);
                                count += value.Length;
                            }
                            else
                            {
                                writer.WriteString(reader.Value);
                            }
                            break;
                        }
                        if (writeNodeBuffer == null)
                        {
                            writeNodeBuffer = new char[0x400];
                        }
                        while ((num2 = reader.ReadValueChunk(writeNodeBuffer, 0, 0x400)) > 0)
                        {
                            if (maxCount > 0)
                            {
                                if ((count + num2) >= maxCount)
                                {
                                    num2 = maxCount - count;
                                    writer.WriteChars(writeNodeBuffer, 0, num2);
                                    if (!String.IsNullOrEmpty(endStr))
                                    {
                                        writer.WriteString(endStr);
                                    }
                                    finished = true;
                                }
                                else
                                {
                                    writer.WriteChars(writeNodeBuffer, 0, num2);
                                }
                                count += num2;
                            }
                            else
                            {
                                writer.WriteChars(writeNodeBuffer, 0, num2);
                            }
                        }
                        break;

                    case XmlNodeType.CDATA:
                        writer.WriteCData(reader.Value);
                        break;

                    case XmlNodeType.EntityReference:
                        writer.WriteEntityRef(reader.Name);
                        break;

                    case XmlNodeType.ProcessingInstruction:
                    case XmlNodeType.XmlDeclaration:
                        writer.WriteProcessingInstruction(reader.Name, reader.Value);
                        break;

                    case XmlNodeType.Comment:
                        writer.WriteComment(reader.Value);
                        break;

                    case XmlNodeType.DocumentType:
                        writer.WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
                        break;

                    case XmlNodeType.Whitespace:
                    case XmlNodeType.SignificantWhitespace:
                        writer.WriteWhitespace(reader.Value);
                        break;

                    case XmlNodeType.EndElement:
                        if (skipHtmlNode && reader.Name != null && reader.Name.ToLower() == "html")
                        {
                            break;
                        }
                        writer.WriteFullEndElement();
                        break;
                    }
                }while(!finished && reader.Read() && ((num < reader.Depth) || ((num == reader.Depth) && (reader.NodeType == XmlNodeType.EndElement))));
            }
        }
예제 #10
0
 public override void WriteEntityRef(string name)
 {
     _me.WriteEntityRef(name); _bu.WriteEntityRef(name);
 }
예제 #11
0
        protected virtual List <RelationShip> CopyPart(XmlReader xtr, XmlTextWriter xtw, string ns, string partName, ZipReader archive)
        {
            bool isInRel             = false;
            bool extractRels         = ns.Equals(RELATIONSHIP_NS);
            List <RelationShip> rels = new List <RelationShip>();

            RelationShip rel = new RelationShip();

            while (xtr.Read())
            {
                switch (xtr.NodeType)
                {
                case XmlNodeType.Attribute:
                    break;

                case XmlNodeType.CDATA:
                    xtw.WriteCData(xtr.Value);
                    break;

                case XmlNodeType.Comment:
                    xtw.WriteComment(xtr.Value);
                    break;

                case XmlNodeType.DocumentType:
                    xtw.WriteDocType(xtr.Name, null, null, null);
                    break;

                case XmlNodeType.Element:
                    if (extractRels && xtr.LocalName == "Relationship" && xtr.NamespaceURI == RELATIONSHIP_NS)
                    {
                        isInRel = true;
                        rel     = new RelationShip();
                    }

                    xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                    if (xtr.HasAttributes)
                    {
                        while (xtr.MoveToNextAttribute())
                        {
                            if (extractRels && isInRel)
                            {
                                if (xtr.LocalName == "Type")
                                {
                                    rel.Type = xtr.Value;
                                }
                                else if (xtr.LocalName == "Target")
                                {
                                    rel.Target = xtr.Value;
                                }
                                else if (xtr.LocalName == "Id")
                                {
                                    rel.Id = xtr.Value;
                                }
                            }

                            if (!xtr.LocalName.StartsWith("rsid"))
                            {
                                xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, xtr.Value);
                            }
                        }
                        xtr.MoveToElement();
                    }

                    if (isInRel)
                    {
                        isInRel = false;
                        rels.Add(rel);
                    }

                    if (xtr.IsEmptyElement)
                    {
                        xtw.WriteEndElement();
                    }
                    break;

                case XmlNodeType.EndElement:
                    xtw.WriteEndElement();
                    break;

                case XmlNodeType.EntityReference:
                    xtw.WriteEntityRef(xtr.Name);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    xtw.WriteProcessingInstruction(xtr.Name, xtr.Value);
                    break;

                case XmlNodeType.SignificantWhitespace:
                    xtw.WriteWhitespace(xtr.Value);
                    break;

                case XmlNodeType.Text:
                    xtw.WriteString(xtr.Value);
                    break;

                case XmlNodeType.Whitespace:
                    xtw.WriteWhitespace(xtr.Value);
                    break;

                case XmlNodeType.XmlDeclaration:
                    // omit XML declaration
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }
            }
            return(rels);
        }
예제 #12
0
 public override void WriteEntityRef(string name)
 {
     _originalWriter.WriteEntityRef(name);
     _buffer.WriteEntityRef(name);
 }
예제 #13
0
 public override void WriteEntityRef(string name)
 {
     xmlWriter.WriteEntityRef(name);
 }
예제 #14
0
 public override void WriteEntityRef(String name)
 {
     base.WriteEntityRef(name);
     _logWriter.WriteEntityRef(name);
 }
예제 #15
0
        protected override List <RelationShip> CopyPart(XmlReader xtr, XmlTextWriter xtw, string ns, string partName, ZipReader archive)
        {
            bool isInRel                = false;
            bool extractRels            = ns.Equals(RELATIONSHIP_NS);
            bool fieldBegin             = false;
            bool isInIndex              = false;
            List <RelationShip> rels    = new List <RelationShip>();
            Stack <string>      context = new Stack <string>();

            XmlDocument xmlDocument  = new XmlDocument();
            XmlNode     bookmarkNode = null;

            RelationShip rel = new RelationShip();

            while (xtr.Read())
            {
                switch (xtr.NodeType)
                {
                case XmlNodeType.Attribute:
                    break;

                case XmlNodeType.CDATA:
                    xtw.WriteCData(xtr.Value);
                    break;

                case XmlNodeType.Comment:
                    xtw.WriteComment(xtr.Value);
                    break;

                case XmlNodeType.DocumentType:
                    xtw.WriteDocType(xtr.Name, null, null, null);
                    break;

                case XmlNodeType.Element:
                    if (extractRels && xtr.LocalName == "Relationship" && xtr.NamespaceURI == RELATIONSHIP_NS)
                    {
                        isInRel = true;
                        rel     = new RelationShip();
                    }

                    if ((xtr.Name.Equals("w:bookmarkEnd") || xtr.Name.Equals("w:bookmarkStart")) &&
                        (xtr.Depth == 1 || (ns.Equals("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") && xtr.Depth == 2)))
                    {
                        // opening and closing bookmark tags below w:body (or below w:hdr, w:ftr, w:footnotes etc) will be moved inside the following w:p tag
                        // because in ODF bookmarks can only be opened and closed in paragraph-content
                        bookmarkNode = xmlDocument.CreateElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);
                        if (xtr.HasAttributes)
                        {
                            while (xtr.MoveToNextAttribute())
                            {
                                XmlAttribute xmlAttribute = xmlDocument.CreateAttribute(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);
                                xmlAttribute.Value = xtr.Value;
                                bookmarkNode.Attributes.Append(xmlAttribute);
                            }
                        }
                    }
                    else if (!xtr.LocalName.Equals("proofErr"))
                    {
                        context.Push(xtr.Name);
                        xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                        if (xtr.HasAttributes)
                        {
                            while (xtr.MoveToNextAttribute())
                            {
                                if (extractRels && isInRel)
                                {
                                    if (xtr.LocalName == "Type")
                                    {
                                        rel.Type = xtr.Value;
                                    }
                                    else if (xtr.LocalName == "Target")
                                    {
                                        rel.Target = xtr.Value;
                                    }
                                    else if (xtr.LocalName == "Id")
                                    {
                                        rel.Id = xtr.Value;
                                    }
                                }

                                if (!xtr.LocalName.StartsWith("rsid"))
                                {
                                    string value = xtr.Value;
                                    // normalize type ST_OnOff
                                    if (value == "on" || value == "true")
                                    {
                                        value = "1";
                                    }
                                    else if (value == "off" || value == "false")
                                    {
                                        value = "0";
                                    }

                                    xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, value);
                                }

                                switch (xtr.LocalName)
                                {
                                case "fldCharType":
                                    if (xtr.Value.Equals("begin"))
                                    {
                                        fieldBegin = true;
                                        _insideField++;
                                        _fieldId++;
                                    }
                                    if (xtr.Value.Equals("end"))
                                    {
                                        fieldBegin = false;
                                        _insideField--;
                                        if (_insideField == 0)
                                        {
                                            isInIndex = false;
                                        }
                                    }
                                    break;

                                case "fldLock":
                                    _fieldLocked = (xtr.Value.Equals("on") || xtr.Value.Equals("true") || xtr.Value.Equals("1")) ? 1 : 0;
                                    break;
                                }
                            }
                            xtr.MoveToElement();
                        }

                        if (isInRel)
                        {
                            isInRel = false;
                            rels.Add(rel);
                        }

                        switch (xtr.LocalName)
                        {
                        case "p":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, _paraId.ToString());
                            xtw.WriteAttributeString(NS_PREFIX, "s", PACKAGE_NS, _sectPrId.ToString());
                            _paraId++;

                            if (bookmarkNode != null)
                            {
                                xtw.WriteStartElement(bookmarkNode.Prefix, bookmarkNode.LocalName, bookmarkNode.NamespaceURI);

                                foreach (XmlAttribute attrib in bookmarkNode.Attributes)
                                {
                                    xtw.WriteAttributeString(attrib.Prefix, attrib.LocalName, attrib.NamespaceURI, attrib.Value);
                                }
                                xtw.WriteEndElement();
                                bookmarkNode = null;
                            }

                            // re-trigger field translation for fields spanning across multiple paragraphs
                            if (_insideField > 0)
                            {
                                fieldBegin = true;
                            }

                            if (isInIndex)
                            {
                                xtw.WriteAttributeString(NS_PREFIX, "index", PACKAGE_NS, "1");
                            }

                            break;

                        case "altChunk":
                        case "bookmarkEnd":
                        case "bookmarkStart":
                        case "commentRangeEnd":
                        case "commentRangeStart":
                        case "del":
                        case "ins":
                        case "moveFrom":
                        case "moveFromRangeEnd":
                        case "moveFromRangeStart":
                        case "moveToRangeEnd":
                        case "moveToRangeStart":
                        case "oMath":
                        case "oMathPara":
                        case "permEnd":
                        case "permStart":
                        case "proofErr":
                        case "sdt":
                        case "tbl":
                            // write the id of the following w:p
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, _paraId.ToString());

                            // write the id of the current section
                            xtw.WriteAttributeString(NS_PREFIX, "s", PACKAGE_NS, _sectPrId.ToString());
                            break;

                        case "r":
                            if (_insideField > 0)
                            {
                                // add an attribute if we are inside a field definition
                                xtw.WriteAttributeString(NS_PREFIX, "f", PACKAGE_NS, _insideField.ToString());
                                xtw.WriteAttributeString(NS_PREFIX, "fid", PACKAGE_NS, _fieldId.ToString());

                                // also add the id of the current paragraph so we can get the display value of the
                                // field for a specific paragraph easily. This is to support multi-paragraph fields.
                                xtw.WriteAttributeString(NS_PREFIX, "fpid", PACKAGE_NS, _paraId.ToString());

                                // also add a marker indicating whether a field is locked or not
                                xtw.WriteAttributeString(NS_PREFIX, "flocked", PACKAGE_NS, _fieldLocked.ToString());

                                if (fieldBegin)
                                {
                                    // add markup to the first run of a field so that we can trigger field
                                    // translation later in template InsertComplexField
                                    // This is also used to support multi-paragraph fields.
                                    //
                                    xtw.WriteAttributeString(NS_PREFIX, "fStart", PACKAGE_NS, "1");
                                    fieldBegin   = false;
                                    _fieldLocked = 0;
                                }
                            }
                            break;

                        case "sectPr":
                            xtw.WriteAttributeString(NS_PREFIX, "s", PACKAGE_NS, _sectPrId.ToString());
                            _sectPrId++;
                            break;

                        case "fldSimple":
                            if (!xtr.IsEmptyElement)
                            {
                                _insideField++;
                            }
                            break;
                        }

                        if (xtr.IsEmptyElement)
                        {
                            xtw.WriteEndElement();
                            context.Pop();
                        }
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (xtr.LocalName.Equals("fldSimple"))
                    {
                        _insideField--;
                    }
                    if (!xtr.LocalName.Equals("proofErr"))
                    {
                        xtw.WriteEndElement();
                        context.Pop();
                    }
                    if (_insideField == 0)
                    {
                        isInIndex = false;
                    }
                    break;

                case XmlNodeType.EntityReference:
                    xtw.WriteEntityRef(xtr.Name);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    xtw.WriteProcessingInstruction(xtr.Name, xtr.Value);
                    break;

                case XmlNodeType.SignificantWhitespace:
                    xtw.WriteWhitespace(xtr.Value);
                    break;

                case XmlNodeType.Text:
                    if (context.Count > 0 && context.Peek().Equals("w:instrText"))
                    {
                        if (xtr.Value.ToUpper().Contains("TOC") || xtr.Value.ToUpper().Contains("BIBLIOGRAPHY") || xtr.Value.ToUpper().Contains("INDEX"))
                        {
                            isInIndex = true;
                        }
                    }
                    xtw.WriteString(xtr.Value);
                    break;

                case XmlNodeType.Whitespace:
                    xtw.WriteWhitespace(xtr.Value);
                    break;

                case XmlNodeType.XmlDeclaration:
                    // omit XML declaration
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }
            }

            _paraId++;
            _sectPrId++;

            return(rels);
        }
예제 #16
0
 public void WriteEntityReference(string name)
 {
     _writer.WriteEntityRef(name);
 }
예제 #17
0
        protected override List <RelationShip> CopyPart(XmlReader xtr, XmlTextWriter xtw, string ns, string partName, ZipReader archive)
        {
            bool isInRel             = false;
            bool extractRels         = ns.Equals(RELATIONSHIP_NS);
            bool isCell              = false;
            List <RelationShip> rels = new List <RelationShip>();

            int idSheet     = 0;
            int idRow       = 1;
            int idFont      = 0;
            int idFill      = 0;
            int idBorder    = 0;
            int idXf        = 0;
            int idCellStyle = 0;
            int idDxf       = 0;
            int idSi        = 0;
            int idCf        = 0;

            int RowNumber     = 0;
            int PrevRowNumber = 0;

            int ColNumber     = 0;
            int PrevColNumber = 0;

            String     ConditionalCell        = "";
            String     ConditionalCellRow     = "";
            List <int> ConditionalCellRowList = new List <int>();
            Boolean    CheckIfBigConditional  = new Boolean();

            intConditionalWithStyle = new Hashtable();
            string s = "";
            int    ConditionalStyle = -1;

            XmlReader SearchConditionalReader;

            RelationShip rel = new RelationShip();

            if (!(partName.Contains(".vml")))
            {
                while (xtr.Read())
                {
                    switch (xtr.NodeType)
                    {
                    case XmlNodeType.Attribute:
                        break;

                    case XmlNodeType.CDATA:
                        xtw.WriteCData(xtr.Value);
                        break;

                    case XmlNodeType.Comment:
                        xtw.WriteComment(xtr.Value);
                        break;

                    case XmlNodeType.DocumentType:
                        xtw.WriteDocType(xtr.Name, null, null, null);
                        break;

                    case XmlNodeType.Element:
                        if (String.Compare(xtr.LocalName, "sheetData") == 0)
                        {
                            SearchConditionalReader = XmlReader.Create(archive.GetEntry(partName));
                            ConditionalCell         = Conditional(SearchConditionalReader, ns, partName);
                            CheckIfBigConditional   = CheckIfBigConditionalRow(ConditionalCell);

                            if (!CheckIfBigConditional)
                            {
                                ConditionalCellRowList = ConditionalCellRowNumberList(ConditionalCell);
                            }

                            ConditionalCellRowList.Sort();
                        }

                        if (extractRels && xtr.LocalName == "Relationship" && xtr.NamespaceURI == RELATIONSHIP_NS)
                        {
                            isInRel = true;
                            rel     = new RelationShip();
                        }

                        if (xtr.LocalName.Equals("row") && (ConditionalCell != ""))
                        {
                            if (xtr.HasAttributes)
                            {
                                while (xtr.MoveToNextAttribute())
                                {
                                    if (xtr.LocalName.Equals("r"))
                                    {
                                        RowNumber = System.Int32.Parse(xtr.Value.ToString());
                                    }
                                }

                                InsertEmptyRowsWithConditional(ConditionalCellRowList, ConditionalCell, xtw, RowNumber, PrevRowNumber, CheckIfBigConditional, false);
                                xtr.MoveToElement();

                                xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                                if (xtr.HasAttributes)
                                {
                                    while (xtr.MoveToNextAttribute())
                                    {
                                        xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, xtr.Value);
                                    }
                                }

                                xtr.MoveToElement();
                            }
                            PrevRowNumber = RowNumber;
                        }
                        else
                        {
                            isCell = xtr.LocalName.Equals("c") && xtr.NamespaceURI.Equals(SPREADSHEET_ML_NS);

                            if (xtr.HasAttributes && isCell && ConditionalCell != "" && ConditionalCellRowList.Contains(RowNumber))
                            {
                                while (xtr.MoveToNextAttribute())
                                {
                                    if (xtr.LocalName == "r")
                                    {
                                        ColNumber = GetColId(xtr.Value);
                                        InsertCellInRow(RowNumber, ConditionalCell, xtw, PrevColNumber, ColNumber);
                                        PrevColNumber = ColNumber;
                                    }
                                }
                                xtr.MoveToElement();
                            }

                            xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                            if (xtr.HasAttributes)
                            {
                                while (xtr.MoveToNextAttribute())
                                {
                                    if (extractRels && isInRel)
                                    {
                                        if (xtr.LocalName == "Type")
                                        {
                                            rel.Type = xtr.Value;
                                        }
                                        else if (xtr.LocalName == "Target")
                                        {
                                            rel.Target = xtr.Value;
                                        }
                                        else if (xtr.LocalName == "Id")
                                        {
                                            rel.Id = xtr.Value;
                                        }
                                    }

                                    string value = xtr.Value;
                                    // normalize type ST_OnOff
                                    if (value == "on" || value == "true")
                                    {
                                        value = "1";
                                    }
                                    else if (value == "off" || value == "false")
                                    {
                                        value = "0";
                                    }

                                    xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, value);

                                    switch (xtr.LocalName)
                                    {
                                    case "r":
                                        if (isCell)
                                        {
                                            string coord = GetColId(value).ToString(System.Globalization.CultureInfo.InvariantCulture)
                                                           + "|"
                                                           + GetRowId(value).ToString(System.Globalization.CultureInfo.InvariantCulture);

                                            xtw.WriteAttributeString(NS_PREFIX, "p", PACKAGE_NS, coord);
                                            if (ConditionalCell != "" && ConditionalCellRowList.Contains(GetRowId(value)))
                                            {
                                                ConditionalStyle = CheckIfConditional(GetRowId(value), GetColId(value), ConditionalCell);
                                                if (ConditionalStyle != -1)
                                                {
                                                    xtw.WriteAttributeString(NS_PREFIX, "ConditionalStyle", PACKAGE_NS, ConditionalStyle.ToString());
                                                }
                                            }
                                            //xtw.WriteAttributeString(NS_PREFIX, "c", PACKAGE_NS, GetColId(value).ToString(System.Globalization.CultureInfo.InvariantCulture));
                                            //xtw.WriteAttributeString(NS_PREFIX, "r", PACKAGE_NS, GetRowId(value).ToString(System.Globalization.CultureInfo.InvariantCulture));
                                        }
                                        break;

                                    case "s":
                                        s = xtr.Value;
                                        break;
                                    }
                                }


                                if (ConditionalStyle > -1)
                                {
                                    if (intConditionalWithStyle.Contains(ConditionalStyle))
                                    {
                                        String OldValue = Convert.ToString(intConditionalWithStyle[ConditionalStyle]);

                                        if (!("|" + OldValue).Contains("|" + s + "|"))
                                        {
                                            intConditionalWithStyle.Remove(ConditionalStyle);
                                            intConditionalWithStyle.Add(ConditionalStyle, (OldValue + s + "|"));
                                        }
                                    }
                                    else
                                    {
                                        intConditionalWithStyle.Add(ConditionalStyle, (s + "|"));
                                    }
                                }

                                ConditionalStyle = -1;

                                xtr.MoveToElement();
                            }
                        }

                        if (isInRel)
                        {
                            isInRel = false;
                            rels.Add(rel);
                        }

                        switch (xtr.LocalName)
                        {
                        // reset id counters
                        case "sheets": idSheet = 0; break;

                        case "sheetData": idRow = 1; break;

                        case "fonts": idFont = 0; break;

                        case "fills": idFill = 0; break;

                        case "borders": idBorder = 0; break;

                        case "cellXfs":
                        case "cellStyleXfs":
                            idXf = 0;
                            break;

                        case "cellStyles": idCellStyle = 0; break;

                        case "dxfs": idDxf = 0; break;

                        case "sst": idSi = 0; break;

                        // add id values
                        case "sheet":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idSheet++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "row":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idRow++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "font":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idFont++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "fill":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idFill++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "border":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idBorder++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "xf":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idXf++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "cellStyle":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idCellStyle++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "dxf":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idDxf++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "si":     // sharedStrings
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idSi++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "worksheet":
                        case "chartSpace":
                            xtw.WriteAttributeString(NS_PREFIX, "part", PACKAGE_NS, _partId.ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "conditionalFormatting":
                            xtw.WriteAttributeString(NS_PREFIX, "part", PACKAGE_NS, _partId.ToString(System.Globalization.CultureInfo.InvariantCulture));
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idCf++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            if (intConditionalWithStyle.Contains(idCf - 1))
                            {
                                xtw.WriteAttributeString(NS_PREFIX, "ConditionalInheritance", PACKAGE_NS, Convert.ToString(intConditionalWithStyle[idCf - 1]));
                            }
                            break;

                        case "col":
                        case "sheetFormatPr":
                        case "mergeCell":
                        case "drawing":
                        case "hyperlink":

                        case "ser":
                        case "val":
                        case "xVal":
                        case "cat":
                        case "plotArea":
                        case "grouping":
                        case "spPr":
                        case "errBars":
                            xtw.WriteAttributeString(NS_PREFIX, "part", PACKAGE_NS, _partId.ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;
                        }

                        if (xtr.IsEmptyElement)
                        {
                            if (ConditionalCell != "" && string.Compare(xtr.LocalName.ToString(), "sheetData") == 0)
                            {
                                InsertEmptyRowsWithConditional(ConditionalCellRowList, ConditionalCell, xtw, 65537, 0, CheckIfBigConditional, false);
                            }

                            xtw.WriteEndElement();
                        }
                        break;

                    case XmlNodeType.EndElement:
                        if (string.Compare(xtr.LocalName.ToString(), "sheetData") == 0 && (ConditionalCell != ""))
                        {
                            InsertEmptyRowsWithConditional(ConditionalCellRowList, ConditionalCell, xtw, 65537, PrevRowNumber, CheckIfBigConditional, true);
                        }
                        if (string.Compare(xtr.LocalName.ToString(), "row") == 0 && (ConditionalCell != ""))
                        {
                            InsertCellInRow(RowNumber, ConditionalCell, xtw, PrevColNumber, 257);
                        }

                        xtw.WriteEndElement();
                        break;

                    case XmlNodeType.EntityReference:
                        xtw.WriteEntityRef(xtr.Name);
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        xtw.WriteProcessingInstruction(xtr.Name, xtr.Value);
                        break;

                    case XmlNodeType.SignificantWhitespace:
                        xtw.WriteWhitespace(xtr.Value);
                        break;

                    case XmlNodeType.Text:
                        xtw.WriteString(xtr.Value);
                        break;

                    case XmlNodeType.Whitespace:
                        xtw.WriteWhitespace(xtr.Value);
                        break;

                    case XmlNodeType.XmlDeclaration:
                        // omit XML declaration
                        break;

                    default:
                        Debug.Assert(false);
                        break;
                    }
                }
            }

            _partId++;

            return(rels);
        }
예제 #18
0
        static void CreateXML(string file)
        {
            XmlTextWriter writer = null;

            try
            {
                writer            = new XmlTextWriter(file, Encoding.Unicode);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                {
                    //< !DOCTYPE clients[<!ENTITY hello "Привіт з Ощад! " >] >
                    writer.WriteDocType("students", null, null, "<!ENTITY hello \"Привіт з Ощад! \">");
                    writer.WriteStartElement("students");
                    {
                        writer.WriteStartElement("student");
                        {
                            writer.WriteComment("Тест коментаря");
                            writer.WriteStartElement("fname");
                            {
                                writer.WriteEntityRef("hello");
                                writer.WriteString("Ivan");
                                writer.WriteEndElement();
                            }
                            writer.WriteElementString("lname", "Ivasyk");
                            writer.WriteElementString("suma", "10.59");
                            writer.WriteStartElement("address");
                            {
                                writer.WriteAttributeString("country", "Україна");
                                writer.WriteAttributeString("region", "Житомирська область");
                                writer.WriteString("Житомир");
                                writer.WriteEndElement();
                            }

                            writer.WriteElementString("birthday", "15.05.1978");
                        }
                        writer.WriteEndElement();
                        writer.WriteStartElement("student");
                        {
                            writer.WriteComment("Тест коментаря");
                            writer.WriteStartElement("fname");
                            {
                                writer.WriteEntityRef("hello");
                                writer.WriteString("Petro");
                                writer.WriteEndElement();
                            }
                            writer.WriteElementString("lname", "Petrenko");
                            writer.WriteElementString("suma", "1.59");
                            writer.WriteStartElement("address");
                            {
                                writer.WriteAttributeString("country", "Україна");
                                writer.WriteAttributeString("region", "Київська область");
                                writer.WriteString("Київ");
                                writer.WriteEndElement();
                            }

                            writer.WriteElementString("birthday", "15.05.1978");
                        }
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
                writer.WriteEndDocument();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                writer?.Close();
            }
        }
예제 #19
0
        private XmlTextReader ProcessPublishedContext(XmlTextReader xReader, PipelineContext context)
        {
            TextWriter    sWriter = new StringWriter();
            XmlTextWriter xWriter = new XmlTextWriter(sWriter);

            xReader.MoveToContent();

            while (!xReader.EOF)
            {
                switch (xReader.NodeType)
                {
                case XmlNodeType.Element:
                    xWriter.WriteStartElement(xReader.Prefix, xReader.LocalName, xReader.NamespaceURI);
                    xWriter.WriteAttributes(xReader, false);
                    try
                    {
                        if (IsValidItem(xReader))
                        {
                            using (var client = new CoreServiceUtility())
                            {
                                string id     = xReader.GetAttribute("ID"); // Get the id of item from List
                                string catman = "catman-";
                                string bptman = "bptman-";
                                if (id.StartsWith(catman))
                                {
                                    id = id.ToString().Replace(catman, string.Empty);
                                }
                                else if (id.StartsWith(bptman))
                                {
                                    id = id.ToString().Replace(bptman, string.Empty);
                                }
                                TcmUri uri = new TcmUri(id);
                                // Validate the the types of items
                                if (uri.ItemType == ItemType.Component || uri.ItemType == ItemType.Page || uri.ItemType == ItemType.StructureGroup || uri.ItemType == ItemType.Category)
                                {
                                    string        publishedCotexts     = null;
                                    List <string> publishedPurposeList = new List <string>();
                                    try
                                    {
                                        var publishInfo = client.GetListPublishInfo(id);
                                        //Validate item is published
                                        if (publishInfo.Count() > 0)
                                        {
                                            foreach (var info in publishInfo)
                                            {
                                                if (!String.IsNullOrEmpty(info.TargetPurpose))
                                                {
                                                    //Validate item is published from current publication
                                                    if (client.IsPublished(id, info.TargetPurpose))
                                                    {
                                                        publishedPurposeList.Add(info.TargetPurpose);
                                                    }
                                                }
                                                else
                                                {
                                                    Trace.TraceError($"TargetInfo is NUll");
                                                }
                                            }

                                            if (publishedPurposeList.Count > 0)
                                            {
                                                publishedCotexts = String.Join(",", publishedPurposeList.Distinct());
                                                xWriter.WriteAttributeString("PublishedTo", publishedCotexts);     // Add the data into the list
                                            }
                                            else
                                            {
                                                xWriter.WriteAttributeString("PublishedTo", "-");
                                            }
                                        }
                                        else
                                        {
                                            xWriter.WriteAttributeString("PublishedTo", "-");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.TraceError("Exception :" + ex.Message + "Stack Trace :" + ex.StackTrace);
                                    }
                                }
                                else
                                {
                                    xWriter.WriteAttributeString("PublishedTo", "N/A");
                                    xReader.MoveToElement();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Exception: " + ex.Message + "Stack Trace :" + ex.StackTrace);
                    }
                    if (xReader.IsEmptyElement)
                    {
                        xWriter.WriteEndElement();
                    }
                    break;

                case XmlNodeType.EndElement:
                    xWriter.WriteEndElement();
                    break;

                case XmlNodeType.CDATA:
                    xWriter.WriteCData(xReader.Value);
                    break;

                case XmlNodeType.Comment:
                    xWriter.WriteComment(xReader.Value);
                    break;

                case XmlNodeType.DocumentType:
                    xWriter.WriteDocType(xReader.Name, null, null, null);
                    break;

                case XmlNodeType.EntityReference:
                    xWriter.WriteEntityRef(xReader.Name);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    xWriter.WriteProcessingInstruction(xReader.Name, xReader.Value);
                    break;

                case XmlNodeType.SignificantWhitespace:
                    xWriter.WriteWhitespace(xReader.Value);
                    break;

                case XmlNodeType.Text:
                    xWriter.WriteString(xReader.Value);
                    break;

                case XmlNodeType.Whitespace:
                    xWriter.WriteWhitespace(xReader.Value);
                    break;
                }
                xReader.Read();
            }
            ;
            xWriter.Flush();
            xReader = new XmlTextReader(new StringReader(sWriter.ToString()));
            xReader.MoveToContent();
            return(xReader);
        }
예제 #20
0
        public TableXml(TableXsd tableXsd, FileInfo path, FileIndex fileIndex, int tableNo)
            : base(path, fileIndex, tableXsd.Schema, TableNamespace(tableXsd), TableNamespaceLocation(TableNamespace(tableXsd), tableNo))
        {
            path.Refresh();
            if (path.Exists == false)
            {
                // We will now use Document from the base class.
                return;
            }

            // We will now void to load large XML documents (> 32MB) into
            // the memory because this can make an OutOfMemoryException
            // Therefore we will set the Document to NULL and use
            // a XmlTextWriter instead.
            long maxSizeForUsingXmlDocument = 1024 * 1024 * 32;

            if (path.Length < maxSizeForUsingXmlDocument)
            {
                try
                {
                    using (var fileStream = new FileStream(path.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                    {
                        using (var xmlReader = XmlReader.Create(fileStream, CreateXmlReaderSettings(base.Schema, ValidationType.None)))
                        {
                            Document.Load(xmlReader);
                            xmlReader.Close();
                        }
                    }
                    return;
                }
                catch (OutOfMemoryException)
                {
                    Document = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }

            Document = null;

            _shadowFile = new FileInfo($"{path.FullName}.shadow");
            try
            {
                DeleteFile(_shadowFile);

                _shadowFileStream = new FileStream(_shadowFile.FullName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read);
                _xmlTextWriter    = new XmlTextWriter(_shadowFileStream, Encoding.UTF8)
                {
                    Formatting = Formatting.Indented
                };

                using (var sourceFileStream = new FileStream(path.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var xmlReader = XmlReader.Create(sourceFileStream, CreateXmlReaderSettings(base.Schema, ValidationType.None)))
                    {
                        while (xmlReader.Read())
                        {
                            switch (xmlReader.NodeType)
                            {
                            case XmlNodeType.Element:
                                _xmlTextWriter.WriteStartElement(xmlReader.Prefix, xmlReader.LocalName, xmlReader.NamespaceURI);
                                _xmlTextWriter.WriteAttributes(xmlReader, true);
                                if (xmlReader.IsEmptyElement)
                                {
                                    _xmlTextWriter.WriteEndElement();
                                }
                                break;

                            case XmlNodeType.Text:
                                _xmlTextWriter.WriteString(xmlReader.Value);
                                break;

                            case XmlNodeType.Whitespace:
                            case XmlNodeType.SignificantWhitespace:
                                _xmlTextWriter.WriteWhitespace(xmlReader.Value);
                                break;

                            case XmlNodeType.CDATA:
                                _xmlTextWriter.WriteCData(xmlReader.Value);
                                break;

                            case XmlNodeType.EntityReference:
                                _xmlTextWriter.WriteEntityRef(xmlReader.Name);
                                break;

                            case XmlNodeType.XmlDeclaration:
                            case XmlNodeType.ProcessingInstruction:
                                _xmlTextWriter.WriteProcessingInstruction(xmlReader.Name, xmlReader.Value);
                                break;

                            case XmlNodeType.DocumentType:
                                _xmlTextWriter.WriteDocType(xmlReader.Name, xmlReader.GetAttribute("PUBLIC"), xmlReader.GetAttribute("SYSTEM"), xmlReader.Value);
                                break;

                            case XmlNodeType.Comment:
                                _xmlTextWriter.WriteComment(xmlReader.Value);
                                break;

                            case XmlNodeType.EndElement:
                                if (string.Compare(xmlReader.LocalName, "table", StringComparison.Ordinal) == 0)
                                {
                                    break;
                                }
                                _xmlTextWriter.WriteFullEndElement();
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                _xmlTextWriter?.Close();
                _shadowFileStream?.Close();
                _shadowFileStream?.Dispose();

                DeleteFile(_shadowFile);

                throw;
            }
        }