Beispiel #1
0
        public void ReaderWithNsTest()
        {
            using (var stream = GetStream(TestFiles.mcdoc))
                using (var doc = WordprocessingDocument.Open(stream, false))
                    using (var reader = OpenXmlPartReader.Create(doc.MainDocumentPart))
                    {
                        reader.Read();
                        Assert.Equal(15, reader.NamespaceDeclarations.Count());
                        reader.Read();
                        Assert.Empty(reader.NamespaceDeclarations);
                    }

            var xml = "<document xmlns=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><body/></document>";

            using (var r1 = OpenXmlDomReader.Create(new Document(xml)))
            {
                r1.Read();
                Assert.Empty(r1.NamespaceDeclarations);
            }

            xml = "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:body a=\"1\"/></w:document>";
            using (var r1 = OpenXmlDomReader.Create(new Document(xml)))
            {
                r1.Read();
                Assert.Single(r1.NamespaceDeclarations);
                Assert.Empty(r1.Attributes);
                Assert.False(r1.HasAttributes);
                r1.Read();
                Assert.Empty(r1.NamespaceDeclarations);
                Assert.Single(r1.Attributes);
                Assert.True(r1.HasAttributes);
            }
        }
        private void AnalyzeElementUsage(OpenXmlPart part)
        {
            if (this.parsedParts.Contains(part.Uri.ToString()) == true)
            {
                return;
            }
            this.parsedParts.Add(part.Uri.ToString());

            foreach (var id in part.Parts)
            {
                OpenXmlReader reader = null;

                try
                {
                    reader = OpenXmlDomReader.Create(id.OpenXmlPart);
                }
                catch
                {
                    // Skips unread parts such as embedded font
                }

                if (reader != null)
                {
                    try
                    {
                        while (reader.Read() == true)
                        {
                            if (reader.IsStartElement == true)
                            {
                                OpenXmlElement element = reader.LoadCurrentElement();
                                this.AnalyzeElementUsage(element);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        this.Log.Warning(e.Message);
                    }
                }

                this.AnalyzeElementUsage(id.OpenXmlPart);
            }
        }