コード例 #1
0
        /// <summary>
        /// Removes the content controls and keep contents.
        /// </summary>
        /// <param name="document">The document.</param>
        public void RemoveContentControlsAndKeepContents(Document document)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            CustomXmlPartCore customXmlPartCore = new CustomXmlPartCore(this.NamespaceUri);
            CustomXmlPart     customXmlPart     = customXmlPartCore.GetCustomXmlPart(document.MainDocumentPart);
            XmlDocument       customPartDoc     = new XmlDocument();

            if (customXmlPart != null)
            {
                using (XmlReader reader = XmlReader.Create(customXmlPart.GetStream(FileMode.Open, FileAccess.Read)))
                {
                    customPartDoc.Load(reader);
                }
            }

            RemoveContentControlsAndKeepContents(document.Body, customPartDoc.DocumentElement);
            document.Save();
        }
コード例 #2
0
        public void StructuredDocumentTagRangeStartXmlMapping()
        {
            //ExStart:StructuredDocumentTagRangeStartXmlMapping
            Document doc = new Document(MyDir + "Multi-section structured document tags.docx");

            // Construct an XML part that contains data and add it to the document's CustomXmlPart collection.
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Text element #1</text><text>Text element #2</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            Console.WriteLine(Encoding.UTF8.GetString(xmlPart.Data));

            // Create a StructuredDocumentTag that will display the contents of our CustomXmlPart in the document.
            StructuredDocumentTagRangeStart sdtRangeStart = (StructuredDocumentTagRangeStart)doc.GetChild(NodeType.StructuredDocumentTagRangeStart, 0, true);

            // If we set a mapping for our StructuredDocumentTag,
            // it will only display a part of the CustomXmlPart that the XPath points to.
            // This XPath will point to the contents second "<text>" element of the first "<root>" element of our CustomXmlPart.
            sdtRangeStart.XmlMapping.SetMapping(xmlPart, "/root[1]/text[2]", null);

            doc.Save(ArtifactsDir + "WorkingWithSdt.StructuredDocumentTagRangeStartXmlMapping.docx");
            //ExEnd:StructuredDocumentTagRangeStartXmlMapping
        }
コード例 #3
0
        private static void AssertValuesAreAsExpected(
            WordprocessingDocument wordDocument,
            string expectedValue)
        {
            // Retrieve inner text of w:sdt element.
            MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart;
            XElement         sdt          = FindSdtWithTag("Node", mainDocumentPart.GetXElement());
            string           sdtInnerText = GetInnerText(sdt);

            // Retrieve inner text of custom XML element, making the simplifying
            // assumption that we only have a single custom XML part. In reality,
            // we would have to find the custom XML part to which our w:sdt elements
            // are bound among any number of custom XML parts. Further, in our
            // simplified example, we also assume there is a single ex:Node element.
            CustomXmlPart customXmlPart = mainDocumentPart.CustomXmlParts.Single();
            XElement      root          = customXmlPart.GetXElement();
            XElement      node          = root.Elements(Ns + "Node").Single();
            string        nodeInnerText = node.Value;

            // Assert those inner text are indeed equal.
            Assert.Equal(expectedValue, sdtInnerText);
            Assert.Equal(expectedValue, nodeInnerText);
        }
コード例 #4
0
ファイル: WordDocument.cs プロジェクト: mrsunil/bp2
        public virtual T GetCustomXmlPart <T>()
        {
            using (MemoryStream memoryStream = new MemoryStream(_file))
            {
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memoryStream, false))
                {
                    MainDocumentPart mainPart  = wordDoc.MainDocumentPart;
                    CustomXmlPart    myXmlPart = null;
                    foreach (var xmlPart in mainPart.CustomXmlParts)
                    {
                        var exists = false;
                        using (XmlTextReader xReader = new XmlTextReader(xmlPart.GetStream(FileMode.Open, FileAccess.Read)))
                        {
                            xReader.MoveToContent();
                            exists = xReader.NamespaceURI.Equals(AtlasNamespace, StringComparison.InvariantCultureIgnoreCase);
                        }

                        if (exists)
                        {
                            myXmlPart = xmlPart;
                            break;
                        }
                    }

                    if (myXmlPart != null)
                    {
                        var           xmlReader  = XmlReader.Create(myXmlPart.GetStream(FileMode.Open, FileAccess.Read));
                        XmlSerializer serializer = new XmlSerializer(typeof(T), AtlasNamespace);
                        var           metadata   = (T)serializer.Deserialize(xmlReader);

                        return(metadata);
                    }
                }
            }

            return(default(T));
        }
コード例 #5
0
        public void XmlMapping()
        {
            //ExStart
            //ExFor:XmlMapping
            //ExFor:XmlMapping.CustomXmlPart
            //ExFor:XmlMapping.Delete
            //ExFor:XmlMapping.IsMapped
            //ExFor:XmlMapping.PrefixMappings
            //ExFor:XmlMapping.XPath
            //ExSummary:Shows how to set XML mappings for CustomXmlParts.
            Document doc = new Document();

            // Construct an XML part that contains data and add it to the document's CustomXmlPart collection
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Text element #1</text><text>Text element #2</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            Console.WriteLine(Encoding.UTF8.GetString(xmlPart.Data));

            // Create a StructuredDocumentTag that will display the contents of our CustomXmlPart in the document
            StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            // If we set a mapping for our StructuredDocumentTag,
            // it will only display a part of the CustomXmlPart that the XPath points to
            // This XPath will point to the contents second "<text>" element of the first "<root>" element of our CustomXmlPart
            sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[2]", "xmlns:ns='http://www.w3.org/2001/XMLSchema'");

            Assert.True(sdt.XmlMapping.IsMapped);
            Assert.AreEqual(xmlPart, sdt.XmlMapping.CustomXmlPart);
            Assert.AreEqual("/root[1]/text[2]", sdt.XmlMapping.XPath);
            Assert.AreEqual("xmlns:ns='http://www.w3.org/2001/XMLSchema'", sdt.XmlMapping.PrefixMappings);

            // Add the StructuredDocumentTag to the document to display the content from our CustomXmlPart
            doc.FirstSection.Body.AppendChild(sdt);
            doc.Save(ArtifactsDir + "SDT.XmlMapping.docx");
            //ExEnd
        }
コード例 #6
0
            static void GenerateDocument()
            {
                string rootPath         = @"C:\OfficeDocs";
                string xmlDataFile      = @"test.xml";
                string templateDocument = @"temp.docx";
                string outputDocument   = rootPath + @"\MyGeneratedDocument.docx";

                File.Copy(templateDocument, outputDocument);
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(outputDocument, true))
                {
                    //get the main part of the document which contains CustomXMLParts
                    MainDocumentPart mainPart = wordDoc.MainDocumentPart;

                    //delete all CustomXMLParts in the document. If needed only specific CustomXMLParts can be deleted using the CustomXmlParts IEnumerable
                    mainPart.DeleteParts <CustomXmlPart>(mainPart.CustomXmlParts);

                    //add new CustomXMLPart with data from new XML file
                    CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
                    using (FileStream stream = new FileStream(xmlDataFile, FileMode.Open))
                    {
                        myXmlPart.FeedData(stream);
                    }
                }
            }
コード例 #7
0
        public void CreatingCustomXml()
        {
            //ExStart
            //ExFor:CustomXmlPart
            //ExFor:CustomXmlPartCollection.Add(String, String)
            //ExFor:Document.CustomXmlParts
            //ExFor:XmlMapping.SetMapping(CustomXmlPart, String, String)
            //ExSummary:Shows how to create structured document tag with a custom XML data.
            Document doc = new Document();
            // Add test XML data part to the collection.
            CustomXmlPart xmlPart =
                doc.CustomXmlParts.Add(Guid.NewGuid().ToString("B"), "<root><text>Hello, World!</text></root>");

            StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

            doc.FirstSection.Body.AppendChild(sdt);

            doc.Save(MyDir + @"\Artifacts\SDT.CustomXml.docx");
            //ExEnd
            Assert.IsTrue(DocumentHelper.CompareDocs(MyDir + @"\Artifacts\SDT.CustomXml.docx",
                                                     MyDir + @"\Golds\SDT.CustomXml Gold.docx"));
        }
        /// <summary>
        /// Binds content controls to a custom XML part.
        /// </summary>
        /// <param name="document">The WordprocessingDocument.</param>
        /// <param name="part">The custom XML part.</param>
        public static void BindContentControls(this WordprocessingDocument document, CustomXmlPart part)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }
            if (part == null)
            {
                throw new ArgumentNullException("part");
            }

            var customXmlRootElement = part.GetRootElement();
            var storeItemId          = part.CustomXmlPropertiesPart.DataStoreItem.ItemId.Value;

            // Bind w:sdt elements contained in main document part.
            var partRootElement = document.MainDocumentPart.RootElement;

            BindContentControls(partRootElement, customXmlRootElement, storeItemId);
            partRootElement.Save();

            // Bind w:sdt elements contained in header parts.
            foreach (var headerRootElement in document.MainDocumentPart
                     .HeaderParts.Select(p => p.RootElement))
            {
                BindContentControls(headerRootElement, customXmlRootElement, storeItemId);
                headerRootElement.Save();
            }

            // Bind w:sdt elements contained in footer parts.
            foreach (var footerRootElement in document.MainDocumentPart
                     .FooterParts.Select(p => p.RootElement))
            {
                BindContentControls(footerRootElement, customXmlRootElement, storeItemId);
                footerRootElement.Save();
            }
        }
コード例 #9
0
        public void CanUpdateCustomXmlAndMainDocumentPart()
        {
            // Define the initial and updated values of our custom XML element and
            // the data-bound w:sdt element.
            const string initialValue = "VALUE1";
            const string updatedValue = "value2";

            // Create the root element of the custom XML part with the initial value.
            var customXmlRoot =
                new XElement(Ns + "Root",
                             new XAttribute(XNamespace.Xmlns + NsPrefix, NsName),
                             new XElement(Ns + "Node", initialValue));

            // Create the w:sdtContent child element of our w:sdt with the initial value.
            var sdtContent =
                new XElement(W.sdtContent,
                             new XElement(W.p,
                                          new XElement(W.r,
                                                       new XElement(W.t, initialValue))));

            // Create a WordprocessingDocument with the initial values.
            using var stream = new MemoryStream();
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, Type))
            {
                InitializeWordprocessingDocument(wordDocument, customXmlRoot, sdtContent);
            }

            // Assert the WordprocessingDocument has the expected, initial values.
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
            {
                AssertValuesAreAsExpected(wordDocument, initialValue);
            }

            // Update the WordprocessingDocument, using the updated value.
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
            {
                MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart;

                // Change custom XML element, again using the simplifying assumption
                // that we only have a single custom XML part and a single ex:Node
                // element.
                CustomXmlPart customXmlPart = mainDocumentPart.CustomXmlParts.Single();
                XElement      root          = customXmlPart.GetXElement();
                XElement      node          = root.Elements(Ns + "Node").Single();
                node.Value = updatedValue;
                customXmlPart.PutXDocument();

                // Change the w:sdt contained in the MainDocumentPart.
                XElement document = mainDocumentPart.GetXElement();
                XElement sdt      = FindSdtWithTag("Node", document);
                sdtContent = sdt.Elements(W.sdtContent).Single();
                sdtContent.ReplaceAll(
                    new XElement(W.p,
                                 new XElement(W.r,
                                              new XElement(W.t, updatedValue))));

                mainDocumentPart.PutXDocument();
            }

            // Assert the WordprocessingDocument has the expected, updated values.
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
            {
                AssertValuesAreAsExpected(wordDocument, updatedValue);
            }
        }
コード例 #10
0
        public static void InsertCustomXmlForPpt(string pptFileName, string customXML)
        {
            using (PresentationDocument openXmlDoc = PresentationDocument.Open(pptFileName, true))
            {
                // Create a new custom XML part
                int           count         = openXmlDoc.PresentationPart.Parts.Count();
                string        customXmlId   = string.Format("rId{0}", count + 1);
                CustomXmlPart customXmlPart = openXmlDoc.PresentationPart.AddCustomXmlPart(CustomXmlPartType.CustomXml, customXmlId);
                using (Stream outputStream = customXmlPart.GetStream())
                {
                    using (StreamWriter ts = new StreamWriter(outputStream))
                    {
                        ts.Write(customXML);
                    }
                }

                // Add datastore so that the xml will persist after the document is modified
                count = customXmlPart.Parts.Count();
                CustomXmlPropertiesPart customXmlPropertiesPart = customXmlPart.AddNewPart <CustomXmlPropertiesPart>(string.Format("rId{0}", count + 1));
                DataStoreItem           dataStoreItem           = new DataStoreItem()
                {
                    ItemId = string.Format("{0}", Guid.NewGuid())
                };
                dataStoreItem.AddNamespaceDeclaration("ds", "http://schemas.openxmlformats.org/officeDocument/2006/customXml");

                SchemaReferences schemaReferences = new SchemaReferences();
                SchemaReference  schemaReference  = new SchemaReference()
                {
                    Uri = "http://www.w3.org/2001/XMLSchema"
                };

                schemaReferences.Append(schemaReference);
                dataStoreItem.Append(schemaReferences);
                customXmlPropertiesPart.DataStoreItem = dataStoreItem;

                // Add the xml to the customer data section of the document
                CustomerData customerData = new CustomerData()
                {
                    Id = customXmlId
                };
                if (openXmlDoc.PresentationPart.Presentation.CustomerDataList != null)
                {
                    // Sequence matters: http://www.schemacentral.com/sc/ooxml/e-p_custDataLst-1.html
                    if (openXmlDoc.PresentationPart.Presentation.CustomerDataList.Count() > 0)
                    {
                        openXmlDoc.PresentationPart.Presentation.CustomerDataList.InsertBefore(customerData, openXmlDoc.PresentationPart.Presentation.CustomerDataList.FirstChild);
                    }
                    else
                    {
                        openXmlDoc.PresentationPart.Presentation.CustomerDataList.Append(customerData);
                    }
                }
                else
                {
                    CustomerDataList customerDataList = new CustomerDataList();
                    customerDataList.Append(customerData);

                    // Sequence matters: http://www.schemacentral.com/sc/ooxml/e-p_presentation.html
                    if (openXmlDoc.PresentationPart.Presentation.Kinsoku != null)
                    {
                        openXmlDoc.PresentationPart.Presentation.InsertBefore(customerDataList, openXmlDoc.PresentationPart.Presentation.Kinsoku);
                    }
                    else if (openXmlDoc.PresentationPart.Presentation.DefaultTextStyle != null)
                    {
                        openXmlDoc.PresentationPart.Presentation.InsertBefore(customerDataList, openXmlDoc.PresentationPart.Presentation.DefaultTextStyle);
                    }
                    else if (openXmlDoc.PresentationPart.Presentation.ModificationVerifier != null)
                    {
                        openXmlDoc.PresentationPart.Presentation.InsertBefore(customerDataList, openXmlDoc.PresentationPart.Presentation.ModificationVerifier);
                    }
                    else if (openXmlDoc.PresentationPart.Presentation.PresentationExtensionList != null)
                    {
                        openXmlDoc.PresentationPart.Presentation.InsertBefore(customerDataList, openXmlDoc.PresentationPart.Presentation.PresentationExtensionList);
                    }
                    else
                    {
                        openXmlDoc.PresentationPart.Presentation.Append(customerDataList);
                    }
                }
            }
        }
コード例 #11
0
        private void CreateParts(PresentationDocument document, PresentationGenerationData data)
        {
            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart <ExtendedFilePropertiesPart>("rId3");

            GenerateExtendedFilePropertiesPartHelper.GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            PresentationPart presentationPart1 = document.AddPresentationPart();

            GeneratePresentationPartHelper.GeneratePresentationPart1Content(presentationPart1);

            CommentAuthorsPart commentAuthorsPart1 = presentationPart1.AddNewPart <CommentAuthorsPart>("rId8");

            GenerateCommentAuthorsPartHelper.GenerateCommentAuthorsPart1Content(commentAuthorsPart1);

            CustomXmlPart customXmlPart1 = presentationPart1.AddNewPart <CustomXmlPart>("application/xml", "rId3");

            GenerateCustomXmlPartHelper.GenerateCustomXmlPart1Content(customXmlPart1);

            CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart <CustomXmlPropertiesPart>("rId1");

            GenerateCustomXmlPropertiesPartHelper.GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1);

            HandoutMasterPart handoutMasterPart1 = presentationPart1.AddNewPart <HandoutMasterPart>("rId7");

            GenerateHandoutMasterPartHelper.GenerateHandoutMasterPart1Content(handoutMasterPart1);

            ThemePart themePart1 = handoutMasterPart1.AddNewPart <ThemePart>("rId1");

            GenerateThemePartHelper.GenerateThemePart1Content(themePart1);

            TableStylesPart tableStylesPart1 = presentationPart1.AddNewPart <TableStylesPart>("rId12");

            GenerateTableStylesPartHelper.GenerateTableStylesPart1Content(tableStylesPart1);

            CustomXmlPart customXmlPart2 = presentationPart1.AddNewPart <CustomXmlPart>("application/xml", "rId2");

            GenerateCustomXmlPartHelper.GenerateCustomXmlPart2Content(customXmlPart2);

            CustomXmlPropertiesPart customXmlPropertiesPart2 = customXmlPart2.AddNewPart <CustomXmlPropertiesPart>("rId1");

            GenerateCustomXmlPropertiesPartHelper.GenerateCustomXmlPropertiesPart2Content(customXmlPropertiesPart2);

            CustomXmlPart customXmlPart3 = presentationPart1.AddNewPart <CustomXmlPart>("application/xml", "rId1");

            GenerateCustomXmlPartHelper.GenerateCustomXmlPart3Content(customXmlPart3);

            CustomXmlPropertiesPart customXmlPropertiesPart3 = customXmlPart3.AddNewPart <CustomXmlPropertiesPart>("rId1");

            GenerateCustomXmlPropertiesPartHelper.GenerateCustomXmlPropertiesPart3Content(customXmlPropertiesPart3);

            NotesMasterPart notesMasterPart1 = presentationPart1.AddNewPart <NotesMasterPart>("rId6");

            GenerateNotesMasterPartHelper.GenerateNotesMasterPart1Content(notesMasterPart1);

            ThemePart themePart2 = notesMasterPart1.AddNewPart <ThemePart>("rId1");

            GenerateThemePartHelper.GenerateThemePart2Content(themePart2);

            ThemePart themePart3 = presentationPart1.AddNewPart <ThemePart>("rId11");

            GenerateThemePartHelper.GenerateThemePart3Content(themePart3);

            SlidePart slidePart1 = presentationPart1.AddNewPart <SlidePart>("rId5");

            GenerateSlidePartHelper.GenerateSlidePart1Content(slidePart1, data);

            var pictureType = string.Empty;

            if (!string.IsNullOrEmpty(data.PictureType))
            {
                pictureType = data.PictureType;
            }
            else
            {
                pictureType = "image/png";
            }

            ImagePart imagePart1 = slidePart1.AddNewPart <ImagePart>(pictureType, "rId3");

            GenerateImagePartHelper.GenerateImagePart1Content(imagePart1, data.PictureContent);

            NotesSlidePart notesSlidePart1 = slidePart1.AddNewPart <NotesSlidePart>("rId2");

            GenerateNotesSlidePartHelper.GenerateNotesSlidePart1Content(notesSlidePart1);

            notesSlidePart1.AddPart(slidePart1, "rId2");

            notesSlidePart1.AddPart(notesMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart <SlideLayoutPart>("rId1");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart1Content(slideLayoutPart1);

            SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart <SlideMasterPart>("rId1");

            GenerateSlideMasterPartHelper.GenerateSlideMasterPart1Content(slideMasterPart1);

            SlideLayoutPart slideLayoutPart2 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId8");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart2Content(slideLayoutPart2);

            slideLayoutPart2.AddPart(slideMasterPart1, "rId1");

            ImagePart imagePart2 = slideMasterPart1.AddNewPart <ImagePart>("image/jpeg", "rId13");

            GenerateImagePartHelper.GenerateImagePart2Content(imagePart2);

            SlideLayoutPart slideLayoutPart3 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId3");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart3Content(slideLayoutPart3);

            slideLayoutPart3.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart4 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId7");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart4Content(slideLayoutPart4);

            slideLayoutPart4.AddPart(slideMasterPart1, "rId1");

            slideMasterPart1.AddPart(themePart3, "rId12");

            slideMasterPart1.AddPart(slideLayoutPart1, "rId2");

            SlideLayoutPart slideLayoutPart5 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId1");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart5Content(slideLayoutPart5);

            ImagePart imagePart3 = slideLayoutPart5.AddNewPart <ImagePart>("image/jpeg", "rId3");

            GenerateImagePartHelper.GenerateImagePart3Content(imagePart3);

            ImagePart imagePart4 = slideLayoutPart5.AddNewPart <ImagePart>("image/png", "rId2");

            GenerateImagePartHelper.GenerateImagePart4Content(imagePart4);

            slideLayoutPart5.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart6 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId6");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart6Content(slideLayoutPart6);

            slideLayoutPart6.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart7 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId11");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart7Content(slideLayoutPart7);

            slideLayoutPart7.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart8 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId5");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart8Content(slideLayoutPart8);

            slideLayoutPart8.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart9 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId10");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart9Content(slideLayoutPart9);

            slideLayoutPart9.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart10 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId4");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart10Content(slideLayoutPart10);

            slideLayoutPart10.AddPart(slideMasterPart1, "rId1");

            SlideLayoutPart slideLayoutPart11 = slideMasterPart1.AddNewPart <SlideLayoutPart>("rId9");

            GenerateSlideLayoutPartHelper.GenerateSlideLayoutPart11Content(slideLayoutPart11);

            slideLayoutPart11.AddPart(slideMasterPart1, "rId1");

            ViewPropertiesPart viewPropertiesPart1 = presentationPart1.AddNewPart <ViewPropertiesPart>("rId10");

            GenerateViewPropertiesPartHelper.GenerateViewPropertiesPart1Content(viewPropertiesPart1);

            presentationPart1.AddPart(slideMasterPart1, "rId4");

            PresentationPropertiesPart presentationPropertiesPart1 = presentationPart1.AddNewPart <PresentationPropertiesPart>("rId9");

            GeneratePresentationPropertiesPartHelper.GeneratePresentationPropertiesPart1Content(presentationPropertiesPart1);

            CustomFilePropertiesPart customFilePropertiesPart1 = document.AddNewPart <CustomFilePropertiesPart>("rId4");

            CustomFilePropertiesPartHelper.GenerateCustomFilePropertiesPart1Content(customFilePropertiesPart1);

            SetPackageProperties(document);
        }
コード例 #12
0
 /// <summary>
 /// Ink constructor.
 /// </summary>
 /// <param name="ownerPart">The owner part of the Ink.</param>
 internal Ink(CustomXmlPart ownerPart)
     : base(ownerPart)
 {
 }
コード例 #13
0
        public void SetElementFromNameToValueCollectionForType(MainDocumentPart mainDocumentPart, string rootElementName, string childElementName, Dictionary <string, string> nameToValueCollection, NodeType forNodeType)
        {
            if (mainDocumentPart == null)
            {
                throw new ArgumentNullException("mainDocumentPart");
            }

            if (string.IsNullOrEmpty(rootElementName))
            {
                throw new ArgumentNullException("rootElementName");
            }

            if (string.IsNullOrEmpty(childElementName))
            {
                throw new ArgumentNullException("childElementName");
            }

            if (nameToValueCollection == null)
            {
                throw new ArgumentNullException("nameToValueCollection");
            }

            XName         rootElementXName  = XName.Get(rootElementName, this.customXmlPartCore.namespaceUri);
            XName         childElementXName = XName.Get(childElementName, this.customXmlPartCore.namespaceUri);
            XElement      rootElement       = new XElement(rootElementXName);
            XElement      childElement      = null;
            CustomXmlPart customXmlPart     = this.customXmlPartCore.GetCustomXmlPart(mainDocumentPart);

            if (customXmlPart != null)
            {
                // Root element shall never be null if Custom Xml part is present
                rootElement = this.customXmlPartCore.GetFirstElementFromCustomXmlPart(customXmlPart, rootElementName);

                childElement = (from e in rootElement.Descendants(childElementXName)
                                select e).FirstOrDefault();

                if (childElement != null)
                {
                    foreach (KeyValuePair <string, string> idToValue in nameToValueCollection)
                    {
                        if (forNodeType == NodeType.Attribute)
                        {
                            AddOrUpdateAttribute(childElement, idToValue.Key, idToValue.Value);
                        }
                        else if (forNodeType == NodeType.Element)
                        {
                            AddOrUpdateChildElement(childElement, idToValue.Key, idToValue.Value);
                        }
                    }

                    this.customXmlPartCore.WriteElementToCustomXmlPart(customXmlPart, rootElement);
                }
                else
                {
                    childElement = GetElementFromNameToValueCollectionForType(nameToValueCollection, childElementXName, forNodeType);
                    rootElement.Add(childElement);
                }
            }
            else
            {
                customXmlPart = this.customXmlPartCore.AddCustomXmlPart(mainDocumentPart, rootElementName);
                childElement  = GetElementFromNameToValueCollectionForType(nameToValueCollection, childElementXName, forNodeType);
                rootElement.Add(childElement);
            }

            this.customXmlPartCore.WriteElementToCustomXmlPart(customXmlPart, rootElement);
        }
コード例 #14
0
        /// <summary>
        /// Gets the custom XML from the main document part.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <returns>The custom XML as a <see cref="XElement" />.</returns>
        public static XElement GetCustomXml(this MainDocumentPart mainPart)
        {
            CustomXmlPart customXmlPart = mainPart.GetPartsOfType <CustomXmlPart>().FirstOrDefault();

            return(customXmlPart == null ? null : customXmlPart.GetXDocument().Root);
        }
コード例 #15
0
        public void CreatingCustomXml()
        {
            //ExStart
            //ExFor:CustomXmlPart
            //ExFor:CustomXmlPart.Clone
            //ExFor:CustomXmlPart.Data
            //ExFor:CustomXmlPart.Id
            //ExFor:CustomXmlPart.Schemas
            //ExFor:CustomXmlPartCollection
            //ExFor:CustomXmlPartCollection.Add(CustomXmlPart)
            //ExFor:CustomXmlPartCollection.Add(String, String)
            //ExFor:CustomXmlPartCollection.Clear
            //ExFor:CustomXmlPartCollection.Clone
            //ExFor:CustomXmlPartCollection.Count
            //ExFor:CustomXmlPartCollection.GetById(String)
            //ExFor:CustomXmlPartCollection.GetEnumerator
            //ExFor:CustomXmlPartCollection.Item(Int32)
            //ExFor:CustomXmlPartCollection.RemoveAt(Int32)
            //ExFor:Document.CustomXmlParts
            //ExFor:StructuredDocumentTag.XmlMapping
            //ExFor:XmlMapping.SetMapping(CustomXmlPart, String, String)
            //ExSummary:Shows how to create structured document tag with a custom XML data.
            Document doc = new Document();

            // Construct an XML part that contains data and add it to the document's collection
            // Once the "Developer" tab in Microsoft Word is enabled,
            // we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Hello world!</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            // The data we entered is stored in these attributes
            Assert.AreEqual(Encoding.ASCII.GetBytes(xmlPartContent), xmlPart.Data);
            Assert.AreEqual(xmlPartId, xmlPart.Id);

            // XML parts can be referenced by collection index or GUID
            Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
            Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

            // Once the part is created, we can add XML schema associations like this
            xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

            // We can also clone parts and insert them into the collection directly
            CustomXmlPart xmlPartClone = xmlPart.Clone();

            xmlPartClone.Id = Guid.NewGuid().ToString("B");
            doc.CustomXmlParts.Add(xmlPartClone);

            Assert.AreEqual(2, doc.CustomXmlParts.Count);

            // Iterate through collection with an enumerator and print the contents of each part
            using (IEnumerator <CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
            {
                int index = 0;
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
                    Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
                    index++;
                }
            }

            // XML parts can be removed by index
            doc.CustomXmlParts.RemoveAt(1);

            Assert.AreEqual(1, doc.CustomXmlParts.Count);

            // The XML part collection itself can be cloned also
            CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

            // And all elements can be cleared like this
            customXmlParts.Clear();

            // Create a StructuredDocumentTag that will display the contents of our part,
            // insert it into the document and save the document
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            tag.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", string.Empty);

            doc.FirstSection.Body.AppendChild(tag);

            doc.Save(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            //ExEnd

            Assert.IsTrue(DocumentHelper.CompareDocs(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx", GoldsDir + "StructuredDocumentTag.CustomXml Gold.docx"));

            doc     = new Document(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            xmlPart = doc.CustomXmlParts[0];

            Assert.True(Guid.TryParse(xmlPart.Id, out Guid temp));
            Assert.AreEqual("<root><text>Hello world!</text></root>", Encoding.UTF8.GetString(xmlPart.Data));
            Assert.AreEqual("http://www.w3.org/2001/XMLSchema", xmlPart.Schemas[0]);

            tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
            Assert.AreEqual("Hello world!", tag.GetText().Trim());
            Assert.AreEqual("/root[1]/text[1]", tag.XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tag.XmlMapping.PrefixMappings);
        }
コード例 #16
0
 /// <summary>
 /// Loads the DOM from an OpenXML part.
 /// </summary>
 /// <param name="openXmlPart">The part to be loaded.</param>
 public void Load(CustomXmlPart openXmlPart)
 {
     LoadFromPart(openXmlPart);
 }
コード例 #17
0
        private void CreateParts(WordprocessingDocument document)
        {
            DocxBase.CurrentTitle = DocxServiceProvinceRes.Title;

            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart <ExtendedFilePropertiesPart>("rId3");

            DocxBase.GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();

            GenerateMainDocumentPart1Content(mainDocumentPart1);

            FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart <FontTablePart>("rId13");

            DocxBase.GenerateFontTablePart1Content(fontTablePart1);

            StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart <StyleDefinitionsPart>("rId3");

            DocxBase.GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);

            EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart <EndnotesPart>("rId7");

            DocxBase.GenerateEndnotesPart1Content(endnotesPart1);

            FooterPart footerPart1 = mainDocumentPart1.AddNewPart <FooterPart>("rId12");

            DocxBase.GenerateFooterPart1Content(footerPart1);

            NumberingDefinitionsPart numberingDefinitionsPart1 = mainDocumentPart1.AddNewPart <NumberingDefinitionsPart>("rId2");

            DocxBase.GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);

            CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart <CustomXmlPart>("application/xml", "rId1");

            DocxBase.GenerateCustomXmlPart1Content(customXmlPart1);

            CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart <CustomXmlPropertiesPart>("rId1");

            DocxBase.GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1);

            FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart <FootnotesPart>("rId6");

            DocxBase.GenerateFootnotesPart1Content(footnotesPart1);

            HeaderPart headerPart1 = mainDocumentPart1.AddNewPart <HeaderPart>("rId11");

            DocxBase.GenerateHeaderPart1Content(headerPart1);

            WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart <WebSettingsPart>("rId5");

            DocxBase.GenerateWebSettingsPart1Content(webSettingsPart1);

            //ChartPart chartPart1 = mainDocumentPart1.AddNewPart<ChartPart>("rId10");
            //DocxBase.GenerateChartPart1Content(chartPart1);

            //EmbeddedPackagePart embeddedPackagePart1 = chartPart1.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");
            //DocxBase.GenerateEmbeddedPackagePart1Content(embeddedPackagePart1);

            //ChartColorStylePart chartColorStylePart1 = chartPart1.AddNewPart<ChartColorStylePart>("rId2");
            //DocxBase.GenerateChartColorStylePart1Content(chartColorStylePart1);

            //ChartStylePart chartStylePart1 = chartPart1.AddNewPart<ChartStylePart>("rId1");
            //DocxBase.GenerateChartStylePart1Content(chartStylePart1);

            DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart <DocumentSettingsPart>("rId4");

            DocxBase.GenerateDocumentSettingsPart1Content(documentSettingsPart1);

            //ChartPart chartPart2 = mainDocumentPart1.AddNewPart<ChartPart>("rId9");
            //DocxBase.GenerateChartPart2Content(chartPart2);

            //EmbeddedPackagePart embeddedPackagePart2 = chartPart2.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");
            //DocxBase.GenerateEmbeddedPackagePart2Content(embeddedPackagePart2);

            //ChartColorStylePart chartColorStylePart2 = chartPart2.AddNewPart<ChartColorStylePart>("rId2");
            //DocxBase.GenerateChartColorStylePart2Content(chartColorStylePart2);

            //ChartStylePart chartStylePart2 = chartPart2.AddNewPart<ChartStylePart>("rId1");
            //DocxBase.GenerateChartStylePart2Content(chartStylePart2);

            ThemePart themePart1 = mainDocumentPart1.AddNewPart <ThemePart>("rId14");

            DocxBase.GenerateThemePart1Content(themePart1);

            foreach (UsedHyperlink usedHyperlink in DocxBase.UsedHyperlinkList)
            {
                mainDocumentPart1.AddHyperlinkRelationship(new System.Uri(usedHyperlink.URL, System.UriKind.Absolute), true, usedHyperlink.Id.ToString());
            }

            DocxBase.SetPackageProperties(document);
        }
コード例 #18
0
        public void FillTableUsingRepeatingSectionItem()
        {
            //ExStart
            //ExFor:SdtType
            //ExSummary:Shows how to fill a table with data from in an XML part.
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
             
            CustomXmlPart xmlPart = doc.CustomXmlParts.Add("Books",
                                                           "<books>" +
                                                           "<book>" +
                                                           "<title>Everyday Italian</title>" +
                                                           "<author>Giada De Laurentiis</author>" +
                                                           "</book>" +
                                                           "<book>" +
                                                           "<title>The C Programming Language</title>" +
                                                           "<author>Brian W. Kernighan, Dennis M. Ritchie</author>" +
                                                           "</book>" +
                                                           "<book>" +
                                                           "<title>Learning XML</title>" +
                                                           "<author>Erik T. Ray</author>" +
                                                           "</book>" +
                                                           "</books>");
             
            // Create headers for data from the XML content.
            Table table = builder.StartTable();

            builder.InsertCell();
            builder.Write("Title");
            builder.InsertCell();
            builder.Write("Author");
            builder.EndRow();
            builder.EndTable();

            // Create a table with a repeating section inside.
            StructuredDocumentTag repeatingSectionSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);

            repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", string.Empty);
            table.AppendChild(repeatingSectionSdt);

            // Add repeating section item inside the repeating section and mark it as a row.
            // This table will have a row for each element that we can find in the XML document
            // using the "/books[1]/book" XPath, of which there are three.
            StructuredDocumentTag repeatingSectionItemSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);

            repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
             
            Row row = new Row(doc);

            repeatingSectionItemSdt.AppendChild(row);

            // Map XML data with created table cells for the title and author of each book.
            StructuredDocumentTag titleSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", string.Empty);
            row.AppendChild(titleSdt);
             
            StructuredDocumentTag authorSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", string.Empty);
            row.AppendChild(authorSdt);
             
            doc.Save(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");

            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");
            List <StructuredDocumentTag> tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true).OfType <StructuredDocumentTag>().ToList();

            Assert.AreEqual("/books[1]/book", tags[0].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[0].XmlMapping.PrefixMappings);

            Assert.AreEqual(string.Empty, tags[1].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[1].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/title[1]", tags[2].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[2].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/author[1]", tags[3].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[3].XmlMapping.PrefixMappings);

            Assert.AreEqual("Title\u0007Author\u0007\u0007" +
                            "Everyday Italian\u0007Giada De Laurentiis\u0007\u0007" +
                            "The C Programming Language\u0007Brian W. Kernighan, Dennis M. Ritchie\u0007\u0007" +
                            "Learning XML\u0007Erik T. Ray\u0007\u0007", doc.FirstSection.Body.Tables[0].GetText().Trim());
        }
コード例 #19
0
        public void CreatingCustomXml()
        {
            //ExStart
            //ExFor:CustomXmlPart
            //ExFor:CustomXmlPart.Clone
            //ExFor:CustomXmlPart.Data
            //ExFor:CustomXmlPart.Id
            //ExFor:CustomXmlPart.Schemas
            //ExFor:CustomXmlPartCollection
            //ExFor:CustomXmlPartCollection.Add(CustomXmlPart)
            //ExFor:CustomXmlPartCollection.Add(String, String)
            //ExFor:CustomXmlPartCollection.Clear
            //ExFor:CustomXmlPartCollection.Clone
            //ExFor:CustomXmlPartCollection.Count
            //ExFor:CustomXmlPartCollection.GetById(String)
            //ExFor:CustomXmlPartCollection.GetEnumerator
            //ExFor:CustomXmlPartCollection.Item(Int32)
            //ExFor:CustomXmlPartCollection.RemoveAt(Int32)
            //ExFor:Document.CustomXmlParts
            //ExFor:StructuredDocumentTag.XmlMapping
            //ExFor:XmlMapping.SetMapping(CustomXmlPart, String, String)
            //ExSummary:Shows how to create a structured document tag with custom XML data.
            Document doc = new Document();

            // Construct an XML part that contains data and add it to the document's collection.
            // If we enable the "Developer" tab in Microsoft Word,
            // we can find elements from this collection in the "XML Mapping Pane", along with a few default elements.
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Hello world!</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            Assert.AreEqual(Encoding.ASCII.GetBytes(xmlPartContent), xmlPart.Data);
            Assert.AreEqual(xmlPartId, xmlPart.Id);

            // Below are two ways to refer to XML parts.
            // 1 -  By an index in the custom XML part collection:
            Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);

            // 2 -  By GUID:
            Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

            // Add an XML schema association.
            xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

            // Clone a part, and then insert it into the collection.
            CustomXmlPart xmlPartClone = xmlPart.Clone();

            xmlPartClone.Id = Guid.NewGuid().ToString("B");
            doc.CustomXmlParts.Add(xmlPartClone);

            Assert.AreEqual(2, doc.CustomXmlParts.Count);

            // Iterate through the collection and print the contents of each part.
            using (IEnumerator <CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
            {
                int index = 0;
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
                    Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
                    index++;
                }
            }

            // Use the "RemoveAt" method to remove the cloned part by index.
            doc.CustomXmlParts.RemoveAt(1);

            Assert.AreEqual(1, doc.CustomXmlParts.Count);

            // Clone the XML parts collection, and then use the "Clear" method to remove all its elements at once.
            CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

            customXmlParts.Clear();

            // Create a structured document tag that will display our part's contents and insert it into the document body.
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            tag.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", string.Empty);

            doc.FirstSection.Body.AppendChild(tag);

            doc.Save(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            //ExEnd

            Assert.IsTrue(DocumentHelper.CompareDocs(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx", GoldsDir + "StructuredDocumentTag.CustomXml Gold.docx"));

            doc     = new Document(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            xmlPart = doc.CustomXmlParts[0];

            Assert.True(Guid.TryParse(xmlPart.Id, out Guid temp));
            Assert.AreEqual("<root><text>Hello world!</text></root>", Encoding.UTF8.GetString(xmlPart.Data));
            Assert.AreEqual("http://www.w3.org/2001/XMLSchema", xmlPart.Schemas[0]);

            tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
            Assert.AreEqual("Hello world!", tag.GetText().Trim());
            Assert.AreEqual("/root[1]/text[1]", tag.XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tag.XmlMapping.PrefixMappings);
        }
コード例 #20
0
        /// <summary>
        /// Adds the custom XML part to the main document part.
        /// </summary>
        /// <param name="document">The main document part.</param>
        /// <param name="customXml">The custom XML.</param>
        /// <returns>The <see cref="CustomXmlPart" />.</returns>
        public static void AddCustomXmlPart(this MainDocumentPart document, XDocument customXml)
        {
            CustomXmlPart customXmlPart = document.AddNewPart <CustomXmlPart>();

            customXmlPart.PutXDocument(customXml);
        }
コード例 #21
0
 /// <summary>
 /// AdditionalCharacteristics constructor.
 /// </summary>
 /// <param name="ownerPart">The owner part of the AdditionalCharacteristics.</param>
 internal AdditionalCharacteristicsInfo(CustomXmlPart ownerPart)
     : base(ownerPart)
 {
 }
コード例 #22
0
        public void FillTableUsingRepeatingSectionItem()
        {
            //ExStart
            //ExFor:SdtType
            //ExSummary:Shows how to fill the table with data contained in the XML part.
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
             
            CustomXmlPart xmlPart = doc.CustomXmlParts.Add("Books",
                                                           "<books>" +
                                                           "<book><title>Everyday Italian</title>" +
                                                           "<author>Giada De Laurentiis</author></book>" +
                                                           "<book><title>Harry Potter</title>" +
                                                           "<author>J K. Rowling</author></book>" +
                                                           "<book><title>Learning XML</title>" +
                                                           "<author>Erik T. Ray</author></book>" +
                                                           "</books>");
             
            // Create headers for data from xml content
            Table table = builder.StartTable();

            builder.InsertCell();
            builder.Write("Title");
            builder.InsertCell();
            builder.Write("Author");
            builder.EndRow();
            builder.EndTable();
             
            // Create table with RepeatingSection inside
            StructuredDocumentTag repeatingSectionSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);

            repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", "");
            table.AppendChild(repeatingSectionSdt);
             
            // Add RepeatingSectionItem inside RepeatingSection and mark it as a row
            StructuredDocumentTag repeatingSectionItemSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);

            repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
             
            Row row = new Row(doc);

            repeatingSectionItemSdt.AppendChild(row);
             
            // Map xml data with created table cells for book title and author
            StructuredDocumentTag titleSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", "");
            row.AppendChild(titleSdt);
             
            StructuredDocumentTag authorSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", "");
            row.AppendChild(authorSdt);
             
            doc.Save(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");

            //ExEnd
        }
コード例 #23
0
 /// <summary>
 /// Saves the DOM into the OpenXML part.
 /// </summary>
 /// <param name="openXmlPart">The part to be saved to.</param>
 public void Save(CustomXmlPart openXmlPart)
 {
     base.SaveToPart(openXmlPart);
 }
コード例 #24
0
ファイル: Sources.cs プロジェクト: vincent-deng/Open-XML-SDK
 /// <summary>
 /// Sources constructor.
 /// </summary>
 /// <param name="ownerPart">The owner part of the Sources.</param>
 internal Sources(CustomXmlPart ownerPart)
     : base(ownerPart)
 {
 }
コード例 #25
0
        public void FillTableUsingRepeatingSectionItem()
        {
            //ExStart
            //ExFor:SdtType
            //ExSummary:Shows how to fill the table with data contained in the XML part.
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
             
            CustomXmlPart xmlPart = doc.CustomXmlParts.Add("Books",
                                                           "<books>" +
                                                           "<book><title>Everyday Italian</title>" +
                                                           "<author>Giada De Laurentiis</author></book>" +
                                                           "<book><title>Harry Potter</title>" +
                                                           "<author>J. K. Rowling</author></book>" +
                                                           "<book><title>Learning XML</title>" +
                                                           "<author>Erik T. Ray</author></book>" +
                                                           "</books>");
             
            // Create headers for data from xml content
            Table table = builder.StartTable();

            builder.InsertCell();
            builder.Write("Title");
            builder.InsertCell();
            builder.Write("Author");
            builder.EndRow();
            builder.EndTable();
             
            // Create table with RepeatingSection inside
            StructuredDocumentTag repeatingSectionSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);

            repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", string.Empty);
            table.AppendChild(repeatingSectionSdt);
             
            // Add RepeatingSectionItem inside RepeatingSection and mark it as a row
            StructuredDocumentTag repeatingSectionItemSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);

            repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
             
            Row row = new Row(doc);

            repeatingSectionItemSdt.AppendChild(row);
             
            // Map xml data with created table cells for book title and author
            StructuredDocumentTag titleSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", string.Empty);
            row.AppendChild(titleSdt);
             
            StructuredDocumentTag authorSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", string.Empty);
            row.AppendChild(authorSdt);
             
            doc.Save(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");

            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");
            List <StructuredDocumentTag> tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true).OfType <StructuredDocumentTag>().ToList();

            Assert.AreEqual("/books[1]/book", tags[0].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[0].XmlMapping.PrefixMappings);

            Assert.AreEqual(string.Empty, tags[1].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[1].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/title[1]", tags[2].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[2].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/author[1]", tags[3].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[3].XmlMapping.PrefixMappings);

            Assert.AreEqual("Title\u0007Author\u0007\u0007" +
                            "Everyday Italian\u0007Giada De Laurentiis\u0007\u0007" +
                            "Harry Potter\u0007J. K. Rowling\u0007\u0007" +
                            "Learning XML\u0007Erik T. Ray\u0007\u0007", doc.GetChild(NodeType.Table, 0, true).GetText().Trim());
        }
コード例 #26
0
        private XDocument GetXDocument(CustomXmlPart customXmlPart)
        {
            XDocument document = XDocument.Load(customXmlPart.GetStream());

            return(document);
        }