Example #1
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string toConvert = "--aucun--";

            if (!String.IsNullOrEmpty((string)value))
            {
                toConvert = (string)value;
            }
            else
            {
                toConvert = "--aucun--";
            }
            toConvert = Utils.RemoveAccents(toConvert).Trim().ToLower();

            BitmapImage bi3     = new BitmapImage();
            string      _fimage = "";
            //Charge le fichier XML des studios
            XDocument _StudiosXML = XDocument.Load("./Images/Studios/Studios.xml");

            if (_StudiosXML.Nodes() != null)
            {
                //Cherche le studio dans le XML
                var xStudio = from xDef in _StudiosXML.Descendants("name")
                              where xDef.Attribute("searchstring").Value.Contains(toConvert) == true
                              select(string) xDef.Element("icon");

                foreach (string name in xStudio)
                {
                    _fimage = name;
                }

                //Si pas d'image trouvé on prend celle par defaut
                if (_fimage == "")
                {
                    var xDefaut = from xDef in _StudiosXML.Descendants("default")
                                  select(string) xDef.Element("icon");
                    foreach (string name in xDefaut)
                    {
                        _fimage = name;
                    }
                }
            }

            _fimage = "./Images/Studios/" + _fimage;

            bi3.BeginInit();
            bi3.UriSource = new Uri(_fimage, UriKind.Relative);
            bi3.EndInit();
            bi3.Freeze();
            return(bi3);
        }
Example #2
0
        /// <summary>
        /// Processes the document sent via server
        /// </summary>
        /// <returns>Returns a root node that has been calculated from the document</returns>
        public Node ProcessDocument()
        {
            if (document.Nodes() != null)
            {
                foreach (XNode n in document.Nodes())
                {
                    switch (n.NodeType)
                    {
                    case System.Xml.XmlNodeType.Element:
                        count++;
                        location++;
                        ProcessElement(XElement.Parse(n.ToString()), node);
                        location--;
                        break;

                    case System.Xml.XmlNodeType.Comment:
                        ProcessComment(n as XComment, node);
                        break;

                    case System.Xml.XmlNodeType.Text:
                        break;

                    case System.Xml.XmlNodeType.Notation:
                        break;

                    case System.Xml.XmlNodeType.EndElement:
                        break;

                    default:
                        break;
                    }
                }
            }
            Console.WriteLine(location);
            //SortArray(ref node);
            document = null;
            return(node);
        }
Example #3
0
        public static void TraverseTree()
        {
            XDocument doc = CreateEmployeesPrivate();

            Console.WriteLine("-- All nodes --");

            // Iterate over all nodes
            foreach (var node in doc.Nodes())
            {
                Console.WriteLine(node);
            }
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("-- XElement nodes --");

            // Iterate over the XElement nodes
            foreach (var node in doc.Nodes().OfType <XElement>())
            {
                Console.WriteLine(node);
            }
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("-- XComment nodes --");

            // Iterate over only the XComment nodes
            foreach (var node in doc.Nodes().OfType <XComment>())
            {
                Console.WriteLine(node);
            }

            Console.WriteLine(Environment.NewLine);

            Console.WriteLine("-- Employee name nodes --");

            // Iterate over only the XComment nodes
            foreach (var node in doc.Elements("employees").Elements("employee").Elements("name"))
            {
                Console.WriteLine(node);
            }
        }
Example #4
0
        /// <summary>
        /// Reads processing instructions of the loaded file and looks for the schema uri.
        /// If no single uri is extractable, it returnes all processing instructions
        /// </summary>
        /// <param name="_doc">Loaded XDocument</param>
        /// <param name="_otherPIs">Processing instrucions without detectable schema uri</param>
        /// <returns>Schema uri string</returns>
        private static string ReadProcessingInstructions(XDocument _doc, out IEnumerable <XProcessingInstruction> _otherPIs)
        {
            string schemaLocation = string.Empty;

            List <string> schemaLocs = new List <string>();

            IEnumerable <XProcessingInstruction> pIs = (from node in _doc.Nodes().OfType <XProcessingInstruction>() select node);

            Match hrefs;

            //Extract href value from all xml-model processing instructions into a list
            foreach (XProcessingInstruction pImodel in pIs.Where(pI => pI.Target == "xml-model"))
            {
                //Get schemaLocation from pImodel.Data
                //See example here: https://msdn.microsoft.com/de-de/library/t9e807fx(v=vs.110).aspx

                string HRefPattern = "href\\s*=\\s*(?:[\"'](?<1>[^\"']*)[\"']|(?<1>\\S+))";

                try
                {
                    hrefs = Regex.Match(pImodel.Data, HRefPattern,
                                        RegexOptions.IgnoreCase | RegexOptions.Compiled,
                                        TimeSpan.FromSeconds(1));
                    while (hrefs.Success)
                    {
                        schemaLocs.Add(hrefs.Groups[1].ToString());
                        hrefs = hrefs.NextMatch();
                    }
                }

                catch (RegexMatchTimeoutException)
                {
                    break;
                }
            }

            //if all extracted strings are equal, set schemaLocation
            if (schemaLocs.Count > 0 && schemaLocs.Where(loc => loc == schemaLocs[0]).Count() == schemaLocs.Count)
            {
                schemaLocation = schemaLocs[0];
                _otherPIs      = pIs.Where(pI => pI.Target != "xml-model");
            }
            // else, return every processing instruction and leave schemaLocation empty
            else
            {
                _otherPIs = pIs;
            }

            return(schemaLocation);
        }
Example #5
0
        /// <summary>
        /// Invoked for each <see cref="XDocument"/>.
        /// </summary>
        /// <param name="document"></param>
        public virtual void Visit(XDocument document)
        {
            Contract.Requires <ArgumentNullException>(document != null);

            if (document.Declaration != null)
            {
                Visit(document.Declaration);
            }

            foreach (XObject node in document.Nodes())
            {
                Visit(node);
            }
        }
Example #6
0
        public void CreateDocumentCopy()
        {
            Assert.Throws <ArgumentNullException>(() => new XDocument((XDocument)null));

            XDeclaration           declaration = new XDeclaration("1.0", "utf-8", "yes");
            XComment               comment     = new XComment("This is a document");
            XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data");
            XElement               element     = new XElement("RootElement");

            XDocument doc = new XDocument(declaration, comment, instruction, element);

            XDocument doc2 = new XDocument(doc);

            IEnumerator e = doc2.Nodes().GetEnumerator();

            // First node: declaration
            Assert.Equal(doc.Declaration.ToString(), doc2.Declaration.ToString());

            // Next node: comment
            Assert.True(e.MoveNext());
            Assert.IsType <XComment>(e.Current);
            Assert.NotSame(comment, e.Current);

            XComment comment2 = (XComment)e.Current;

            Assert.Equal(comment.Value, comment2.Value);

            // Next node: processing instruction
            Assert.True(e.MoveNext());
            Assert.IsType <XProcessingInstruction>(e.Current);
            Assert.NotSame(instruction, e.Current);

            XProcessingInstruction instruction2 = (XProcessingInstruction)e.Current;

            Assert.Equal(instruction.Target, instruction2.Target);
            Assert.Equal(instruction.Data, instruction2.Data);

            // Next node: element.
            Assert.True(e.MoveNext());
            Assert.IsType <XElement>(e.Current);
            Assert.NotSame(element, e.Current);

            XElement element2 = (XElement)e.Current;

            Assert.Equal(element.Name.ToString(), element2.Name.ToString());
            Assert.Empty(element2.Nodes());

            // Should be end.
            Assert.False(e.MoveNext());
        }
Example #7
0
        static public List <SerialNode> GetSerialNodeList(string XmlPath = "素材合成.exe.config")
        {
            //将XML文件加载进来
            XDocument document = XDocument.Load(XmlPath);

            List <SerialNode> serialNodes = new List <SerialNode>();
            //获取到XML的根元素进行操作
            //  = document.Elements("Flow");
            var firstNodes = document.Nodes();

            foreach (var secondNode in firstNodes)
            {
                foreach (var thirdNode in secondNode.Document.Elements())
                {
                    if (thirdNode.Name == "configuration")
                    {
                        foreach (var fourNode in thirdNode.Elements())
                        {
                            if (fourNode.Name == "SerialNode")
                            {
                                foreach (var fiveNode in fourNode.Elements())
                                {
                                    SerialNode flow = new SerialNode();
                                    foreach (var item in fiveNode.Attributes())
                                    {
                                        if (item.Name == "command")
                                        {
                                            flow.Command = item.Value;
                                        }
                                        if (item.Name == "key")
                                        {
                                            flow.key = item.Value;
                                        }
                                        if (item.Name == "content")
                                        {
                                            flow.Content = item.Value;
                                        }
                                    }
                                    serialNodes.Add(flow);
                                }
                            }
                        }
                    }
                }
            }
            //获取根元素下的所有子元素

            return(serialNodes);
        }
Example #8
0
        private void EnsureAppResourcesLoaded()
        {
            Assembly resourceDescriptionAssembly = Assembly.GetExecutingAssembly();
            //Assembly assembly = Assembly.Load(new AssemblyName(asmName));
            Stream resourcesReferencesStream = resourceDescriptionAssembly.GetManifestResourceStream("VI.Common.Wpf.Res.resources.xml");

            if (resourcesReferencesStream == null)
            {
                return;
            }

            XElement rootItem;

            using (TextReader streamReader = new StreamReader(resourcesReferencesStream))
            {
                XDocument doc = XDocument.Load(streamReader);
                rootItem = doc.Nodes().OfType <XElement>().FirstOrDefault();
            }

            if (rootItem == null)
            {
                return;
            }

            foreach (XElement resourceElement in rootItem.Elements())
            {
                try
                {
                    string asmName    = resourceElement.Attribute("AssemblyName").Value;
                    string typeName   = resourceElement.Attribute("ResourceRegistratorName").Value;
                    string methodName = resourceElement.Attribute("ResourceRegistratorMethodName").Value;

                    Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName.Contains(asmName));

                    //Assembly assembly = Assembly.Load(new AssemblyName(asmName));

                    if (assembly != null)
                    {
                        Type       resourceRegistrator = assembly.GetType(typeName);
                        MethodInfo method = resourceRegistrator.GetMethod(methodName);
                        method.Invoke(null, null);
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("error = {0}", ex.Message));
                }
            }
        }
Example #9
0
        //обновление значений
        public static void Exmpl_09()
        {
            XDocument xDoc = new XDocument(
                new XElement("BookParticipants",
                             new XElement("BookParticipant", new XAttribute("type", "Author")),
                             new XElement("FirstName", "Joe"),
                             new XElement("LastName", "Rattz"),

                             new XElement("BookParticipant", new XAttribute("type", "Editor")),
                             new XElement("FirstName", "Buckingham"),
                             new XElement("LastName", "Rattz"),

                             new XElement("BookParticipant", new XAttribute("type", "Editor")),
                             new XElement("FirstName", "Yevgeniy"),
                             new XElement("LastName", "Gertsen")
                             )
                );

            xDoc.Nodes().OfType <XElement>().Where(w => w.Name == "FirstName").Where(w => w.Value == "Yevgeniy").Single().Value = "Timur";

            var element = xDoc.Nodes().OfType <XElement>().Where(w => w.Name == "FirstName").Single(w => w.Value == "Yevgeniy");

            element.SetValue("5555");
        }
        // Credit: https://stackoverflow.com/questions/42790439/retrieve-processing-instructions-using-xdocument
        private void processPIs(XDocument xDoc, RecordData recordDataIn)
        {
            string xRootPath = xDoc.Root.GetAbsoluteXPath(_indexGroups, _pathDelimiter); // The xml hierachy path

            var pI_nodes = xDoc.Nodes().OfType <XProcessingInstruction>();

            foreach (var pI_node in pI_nodes)
            {
                // Each pI_node is an XNode.
                // Value held is .Data
                string sTarget = pI_node.Target;
                string sData   = pI_node.Data;
                pushRecord(xRootPath + _pathDelimiter + Constants.XML_PI + _attrDelimiter + sTarget,
                           pI_node.Data, recordDataIn);
            }
        }
Example #11
0
        public void Load1()
        {
            string xml = "<?xml version='1.0'?><root />";

            XDocument doc = XDocument.Load(new StringReader(xml));

            Assert.IsTrue(doc.FirstNode is XElement, "#1");
            Assert.IsTrue(doc.LastNode is XElement, "#2");
            Assert.IsNull(doc.NextNode, "#3");
            Assert.IsNull(doc.PreviousNode, "#4");
            Assert.AreEqual(1, new List <XNode> (doc.Nodes()).Count, "#5");
            Assert.IsNull(doc.FirstNode.Parent, "#6");
            Assert.AreEqual(doc.FirstNode, doc.LastNode, "#7");
            Assert.AreEqual(XmlNodeType.Document, doc.NodeType, "#8");
            Assert.AreEqual(doc.FirstNode, doc.Root, "#7");
        }
Example #12
0
        public void ModifyInputData(XDocument input)
        {
            var projRootElem = (XElement)input.Nodes().First();

            foreach (var groupNode in projRootElem.Nodes().OfType <XElement>().Where(obj => obj.Name.LocalName == "ItemGroup"))
            {
                foreach (XElement packageNode in groupNode.Nodes().OfType <XElement>().Where(obj => obj.Name.LocalName == "PackageReference"))
                {
                    var versionNode = packageNode.Nodes().OfType <XElement>().FirstOrDefault(obj => obj.Name.LocalName == "Version");
                    if (versionNode != null)
                    {
                        packageNode.SetAttributeValue("Version", versionNode.Value);
                        versionNode.Remove();
                    }
                }
            }
        }
Example #13
0
        public File ReadXMLFile(string fileName)
        {
            // read from XML file
            XDocument xmlDocument = XDocument.Load(fileName, LoadOptions.SetLineInfo);

            File file = new File()
            {
                FileName = fileName
            };

            // put it in collection using list
            foreach (XElement firstnode in xmlDocument.Nodes())
            {
                if (firstnode.Name == "sitecore")
                {
                    foreach (XElement childNode in firstnode.Nodes())
                    {
                        if (childNode.Name == "phrase")
                        {
                            var lineNumber      = ((IXmlLineInfo)childNode).LineNumber;
                            var attributes      = childNode.Attributes().ToDictionary(x => x.Name, y => y);
                            var key             = attributes.GetValueOrDefault("key")?.Value;
                            var itemId          = attributes.GetValueOrDefault("itemid")?.Value;
                            var path            = attributes.GetValueOrDefault("path")?.Value;
                            var fieldName       = attributes.GetValueOrDefault("fieldName")?.Value;
                            var template        = attributes.GetValueOrDefault("template")?.Value;
                            var translatedValue = childNode.HasElements ? ((XElement)childNode.Nodes().First()).Value : null;

                            Phrase phrase = new Phrase()
                            {
                                LineNumber      = lineNumber,
                                Key             = key,
                                ItemId          = itemId,
                                Path            = path,
                                FieldName       = fieldName,
                                Template        = template,
                                TranslatedValue = translatedValue
                            };

                            file.Phrases.Add(phrase);
                        }
                    }
                }
            }
            return(file);
        }
Example #14
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string toConvert = "--aucun--";

            if (!String.IsNullOrEmpty((string)value))
            {
                toConvert = (string)value;
            }
            else
            {
                toConvert = "--aucun--";
            }
            toConvert = Utils.RemoveAccents(toConvert).Trim();

            BitmapImage bi3     = new BitmapImage();
            string      _fimage = "";
            //Charge le fichier XML des avis
            XDocument _RatingsXML = XDocument.Load("./Images/Ratings/Ratings.xml");

            if (_RatingsXML.Nodes() != null)
            {
                //Cherche l'avis dans le XML
                var xAvis = from xDef in _RatingsXML.Descendants("name")
                            where toConvert.Contains(xDef.Attribute("searchstring").Value) == true
                            select(string) xDef.Element("icon");

                foreach (string name in xAvis)
                {
                    _fimage = name;
                }
            }
            if (String.IsNullOrEmpty(_fimage))
            {
                _fimage = "./Images/blank.png";
            }
            else
            {
                _fimage = "./Images/Ratings/" + _fimage;
            }

            bi3.BeginInit();
            bi3.UriSource = new Uri(_fimage, UriKind.Relative);
            bi3.EndInit();
            bi3.Freeze();
            return(bi3);
        }
        private void AddItem(string type, string value)
        {
            var itemGroups = projectFile
                             .Nodes()
                             .OfType <XElement>()
                             .DescendantNodes()
                             .OfType <XElement>()
                             .Where(x => x.Name.LocalName == "ItemGroup");

            XElement targetItemGroup = null;

            foreach (var itemGroup in itemGroups)
            {
                if (itemGroup.Elements(type).Any())
                {
                    targetItemGroup = itemGroup;
                    break;
                }
            }

            if (targetItemGroup == null)
            {
                foreach (var itemGroup in itemGroups)
                {
                    if (itemGroup.IsEmpty)
                    {
                        targetItemGroup = itemGroup;
                        break;
                    }
                }
            }

            XNamespace rootNamespace = projectFile.Root.Name.NamespaceName;

            if (targetItemGroup == null)
            {
                targetItemGroup = new XElement(rootNamespace + "ItemGroup");
                projectFile.Element("Project").Add(targetItemGroup);
            }

            var xelem = new XElement(rootNamespace + type);

            xelem.Add(new XAttribute("Include", value));
            targetItemGroup.Add(xelem);
        }
Example #16
0
        public void ExecuteXDocumentVariation(XNode[] content, int index)
        {
            XDocument xDoc         = new XDocument(content);
            XDocument xDocOriginal = new XDocument(xDoc);
            XNode     toRemove     = xDoc.Nodes().ElementAt(index);

            using (UndoManager undo = new UndoManager(xDoc))
            {
                undo.Group();
                using (EventsHelper docHelper = new EventsHelper(xDoc))
                {
                    toRemove.Remove();
                    docHelper.Verify(XObjectChange.Remove, toRemove);
                }
                undo.Undo();
                Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
            }
        }
Example #17
0
        /// <summary>
        /// Add standard caption like xml version = etc.
        /// </summary>
        /// <param name="document">Document to modify</param>
        /// <param name="comment">Add standard caption</param>
        public static void AddStandardCaption(this XDocument document,
                                              String comment)
        {
            if (null == document)
            {
                throw new ArgumentNullException(nameof(document));
            }

            XComment xComment = null;

            using var en = document.Nodes().GetEnumerator();

            while (en.MoveNext())
            {
                if (en.Current is XElement)
                {
                    break;
                }

                if (null == xComment)
                {
                    xComment = en.Current as XComment;
                }
            }

            // Creating the declaration
            if (null == document.Declaration)
            {
                document.Declaration = new XDeclaration("1.0", "utf-8", "yes");
            }

            // Changing or creating comment
            if (!String.IsNullOrEmpty(comment))
            {
                if (null == xComment)
                {
                    xComment = new XComment(comment);

                    document.AddFirst(xComment);
                }

                xComment.Value = comment;
            }
        }
Example #18
0
        partial void PublishUIMessageInternal(XElement uiMsgElement)
        {
            var dlg = new ClientMessageWindow(uiMsgElement);

            dlg.Closed += (s, e) =>
            {
                if (dlg.DialogResult.HasValue && dlg.DialogResult.Value)
                {
                    XDocument userDoc = dlg.Result.Document;
                    //XElement action = (XElement)ApplicationEx..DocumentElement;
                    XElement[] sendElt = null;
                    XElement   child   = (XElement)userDoc.FirstNode;

                    if (child.Name == "Request" || child.Name == "Response")
                    {
                        int count = child.Nodes().Count();
                        sendElt = new XElement[count];
                        child   = (XElement)child.FirstNode;
                    }
                    else
                    {
                        sendElt = new XElement[userDoc.Nodes().Count()];
                    }

                    int i = 0;

                    while (child != null)
                    {
                        sendElt[i] = child;
                        child      = (XElement)child.NextNode;
                        i++;
                    }

                    this.CurrentActivity.Exec(sendElt);
                }
                else
                {
                    //ServerApplicationService.Response.Document.Root.RemoveAll();
                    //ServerApplicationService.PublishResponse();
                }
            };

            dlg.Show();
        }
Example #19
0
                /// <summary>
                /// Runs test for valid cases
                /// </summary>
                /// <param name="nodeType">XElement/XAttribute</param>
                /// <param name="name">name to be tested</param>
                public void RunValidTests(string nodeType, string name)
                {
                    XDocument xDocument = new XDocument();
                    XElement  element   = null;

                    try
                    {
                        switch (nodeType)
                        {
                        case "XElement":
                            element = new XElement(name, name);
                            xDocument.Add(element);
                            IEnumerable <XNode> nodeList = xDocument.Nodes();
                            TestLog.Compare(nodeList.Count(), 1, "Failed to create element { " + name + " }");
                            xDocument.RemoveNodes();
                            break;

                        case "XAttribute":
                            element = new XElement(name, name);
                            XAttribute attribute = new XAttribute(name, name);
                            element.Add(attribute);
                            xDocument.Add(element);
                            XAttribute x = element.Attribute(name);
                            TestLog.Compare(x.Name.LocalName, name, "Failed to get the added attribute");
                            xDocument.RemoveNodes();
                            break;

                        case "XName":
                            XName xName = XName.Get(name, name);
                            TestLog.Compare(xName.LocalName.Equals(name), "Invalid LocalName");
                            TestLog.Compare(xName.NamespaceName.Equals(name), "Invalid Namespace Name");
                            TestLog.Compare(xName.Namespace.NamespaceName.Equals(name), "Invalid Namespace Name");
                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        TestLog.WriteLine(nodeType + "failed to create with a valid name { " + name + " }");
                        throw new TestFailedException(e.ToString());
                    }
                }
Example #20
0
        private static IXmpMeta ParseXmlDoc(XDocument document, ParseOptions options)
        {
            object[] result = new object[3];

            result = FindRootNode(document.Nodes(), options.RequireXmpMeta, result);
            if (result != null && result[1] == XmpRdf)
            {
                var xmp = ParseRdf.Parse((XElement)result[0]);
                xmp.SetPacketHeader((string)result[2]);
                // Check if the XMP object shall be normalized
                if (!options.OmitNormalization)
                {
                    return(XmpNormalizer.Process(xmp, options));
                }
                return(xmp);
            }
            // no appropriate root node found, return empty metadata object
            return(new XmpMeta());
        }
Example #21
0
 // https://blogs.msdn.microsoft.com/ericwhite/2009/01/27/equality-semantics-of-linq-to-xml-trees/
 public static XDocument Normalize(XDocument source)
 {
     return(new XDocument(
                source.Declaration,
                source.Nodes().Select(n =>
     {
         // Remove comments, processing instructions, and text nodes that are
         // children of XDocument.  Only white space text nodes are allowed as
         // children of a document, so we can remove all text nodes.
         if (n is XComment || n is XProcessingInstruction || n is XText)
         {
             return null;
         }
         else
         {
             return n is XElement e ? NormalizeElement(e) : n;
         }
     })));
 }
Example #22
0
        /// <summary>
        /// On XDocument
        ///  ~ Empty
        ///  ~ Not empty
        ///      With XDecl
        ///      With DTD
        ///      Just root elem
        ///      Root elem + PI + whitespace + comment
        /// </summary>
        public void OnXDocument1()
        {
            int count = 0;

            _runWithEvents = (bool)Params[0];
            var       xml = Variation.Param as string;
            XDocument e   = xml == "" ? new XDocument() : XDocument.Parse(xml);

            if (_runWithEvents)
            {
                _eHelper = new EventsHelper(e);
                count    = e.Nodes().Count();
            }
            VerifyRemoveNodes(e);
            if (_runWithEvents)
            {
                _eHelper.Verify(XObjectChange.Remove, count);
            }
        }
Example #23
0
        /// <summary>
        /// Parses the XML document by generating the appropriate NSObjects for each XML node.
        /// </summary>
        /// <returns>The root NSObject of the property list contained in the XML document.</returns>
        /// <param name="doc">The XML document.</param>
        static NSObject ParseDocument(XDocument doc, XmlOriginFactory originFactory)
        {
            var docType = doc.Nodes().OfType <XDocumentType>().SingleOrDefault();

            if (docType == null)
            {
                if (!doc.Root?.Name?.LocalName?.Equals("plist") ?? false)
                {
                    throw new XmlException("The given XML document is not a property list.");
                }
            }
            else if (!docType.Name.Equals("plist"))
            {
                throw new XmlException("The given XML document is not a property list.");
            }

            XElement rootNode;

            if (doc.Root?.Name?.LocalName?.Equals("plist") ?? false)
            {
                //Root element wrapped in plist tag
                List <XElement> rootNodes = doc.Root.Elements().ToList();;
                if (rootNodes.Count == 0)
                {
                    throw new PropertyListFormatException("The given XML property list has no root element!");
                }
                if (rootNodes.Count == 1)
                {
                    rootNode = rootNodes[0];
                }
                else
                {
                    throw new PropertyListFormatException("The given XML property list has more than one root element!");
                }
            }
            else
            {
                //Root NSObject not wrapped in plist-tag
                rootNode = doc.Root;
            }

            return(ParseObject(rootNode, originFactory));
        }
Example #24
0
        //[Variation(Priority = 0, Desc = "Nodes from two documents")]

        //[Variation(Priority = 2, Desc = "XDocument.DescendantNodes")]
        public void Document_DescendantNodes()
        {
            int count = 0;

            _runWithEvents = (bool)Params[0];
            XDocument           doc      = XDocument.Load(FilePathUtil.getStream(@"testdata\xlinq\books.xml"), LoadOptions.PreserveWhitespace);
            IEnumerable <XNode> toRemove = doc.DescendantNodes();

            if (_runWithEvents)
            {
                _eHelper = new EventsHelper(doc);
                count    = doc.Nodes().Count();
            }
            VerifyDeleteNodes(toRemove);
            if (_runWithEvents)
            {
                _eHelper.Verify(XObjectChange.Remove, count);
            }
        }
Example #25
0
                /// <summary>
                /// Runs test for InValid cases
                /// </summary>
                /// <param name="nodeType">XElement/XAttribute</param>
                /// <param name="name">name to be tested</param>
                public void RunInValidTests(string nodeType, string name)
                {
                    XDocument xDocument = new XDocument();
                    XElement  element   = null;

                    try
                    {
                        switch (nodeType)
                        {
                        case "XElement":
                            element = new XElement(name, name);
                            xDocument.Add(element);
                            IEnumerable <XNode> nodeList = xDocument.Nodes();
                            break;

                        case "XAttribute":
                            element = new XElement(name, name);
                            XAttribute attribute = new XAttribute(name, name);
                            element.Add(attribute);
                            xDocument.Add(element);
                            XAttribute x = element.Attribute(name);
                            break;

                        case "XName":
                            XName xName = XName.Get(name, name);
                            break;

                        default:
                            break;
                        }
                    }
                    catch (XmlException)
                    {
                        return;
                    }
                    catch (ArgumentException)
                    {
                        return;
                    }

                    // If it gets here then test has failed.
                    throw new TestFailedException(nodeType + "was created with an Invalid name { " + name + " }");
                }
Example #26
0
        // Token: 0x06000F5B RID: 3931 RVA: 0x0005B660 File Offset: 0x00059860
        public XElement ToXElement()
        {
            string text = string.Empty;

            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
                {
                    SplitStateAdapter.Serializer.WriteObject(xmlWriter, this);
                    xmlWriter.Flush();
                    text = stringWriter.ToString();
                }
            }
            XDocument xdocument = XDocument.Parse(text);
            XElement  xelement  = new XElement("SplitState");

            xelement.Add(xdocument.Nodes());
            return(xelement);
        }
        //[Variation(Priority = 0, Desc = "All elements from mixed content")]

        //[Variation(Priority = 0, Desc = "All content from the XDocument (doc level)")]

        public void AllFromDocument()
        {
            int count = 0;

            _runWithEvents = (bool)Params[0];
            XDocument           doc      = XDocument.Parse("\t<?PI?><A xmlns='a'/>\r\n <!--comment-->", LoadOptions.PreserveWhitespace);
            IEnumerable <XNode> toRemove = doc.Nodes();

            if (_runWithEvents)
            {
                _eHelper = new EventsHelper(doc);
                count    = toRemove.IsEmpty() ? 0 : toRemove.Count();
            }
            VerifyDeleteNodes(toRemove);
            if (_runWithEvents)
            {
                _eHelper.Verify(XObjectChange.Remove, count);
            }
        }
        public void Document_Nodes()
        {
            int count = 0;

            _runWithEvents = (bool)Params[0];
            XDocument           doc      = XDocument.Load(FilePathUtil.getStream(Path.Combine("TestData", "XLinq", "Books.xml")), LoadOptions.PreserveWhitespace);
            IEnumerable <XNode> toRemove = doc.Nodes();

            if (_runWithEvents)
            {
                _eHelper = new EventsHelper(doc);
                count    = toRemove.IsEmpty() ? 0 : toRemove.Count();
            }
            VerifyDeleteNodes(toRemove);
            if (_runWithEvents)
            {
                _eHelper.Verify(XObjectChange.Remove, count);
            }
        }
Example #29
0
        /// <summary>
        /// Runs test for InValid cases
        /// </summary>
        /// <param name="nodeType">XElement/XAttribute</param>
        /// <param name="name">name to be tested</param>
        private static void RunInValidTests(string nodeType, string name)
        {
            XDocument xDocument = new XDocument();
            XElement  element   = null;

            try
            {
                switch (nodeType)
                {
                case "XElement":
                    element = new XElement(name, name);
                    xDocument.Add(element);
                    IEnumerable <XNode> nodeList = xDocument.Nodes();
                    break;

                case "XAttribute":
                    element = new XElement(name, name);
                    XAttribute attribute = new XAttribute(name, name);
                    element.Add(attribute);
                    xDocument.Add(element);
                    XAttribute x = element.Attribute(name);
                    break;

                case "XName":
                    XName xName = XName.Get(name, name);
                    break;

                default:
                    break;
                }
            }
            catch (XmlException)
            {
                return;
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.True(false, "Expected exception not thrown");
        }
Example #30
0
                public void ExecuteXDocumentVariation()
                {
                    XNode[]   content      = Variation.Params[0] as XNode[];
                    int       index        = (int)Variation.Params[1];
                    XDocument xDoc         = new XDocument(content);
                    XDocument xDocOriginal = new XDocument(xDoc);
                    XNode     toRemove     = xDoc.Nodes().ElementAt(index);

                    using (UndoManager undo = new UndoManager(xDoc))
                    {
                        undo.Group();
                        using (EventsHelper docHelper = new EventsHelper(xDoc))
                        {
                            toRemove.Remove();
                            docHelper.Verify(XObjectChange.Remove, toRemove);
                        }
                        undo.Undo();
                        TestLog.Compare(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
                    }
                }
Example #31
0
 public static void NodesOnXDocBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText, bText);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XNode> nodes = xDoc.Nodes();
     Assert.Equal(1, nodes.Count());
     a.Remove();
     Assert.Equal(0, nodes.Count());
 }
Example #32
0
 public void SameDocumentDefaultNamespaceSameNameElements()
 {
     XDocument xDoc = new XDocument(new XElement("Name", new XElement("Name")));
     Assert.Same(
         (xDoc.Nodes().First() as XElement).Name.Namespace,
         (xDoc.Nodes().Last() as XElement).Name.Namespace);
     Assert.Same((xDoc.Nodes().First() as XElement).Name, (xDoc.Nodes().Last() as XElement).Name);
 }
Example #33
0
        /// <summary>
        /// Runs test for InValid cases
        /// </summary>
        /// <param name="nodeType">XElement/XAttribute</param>
        /// <param name="name">name to be tested</param>
        public void RunInValidTests(string nodeType, string name)
        {
            XDocument xDocument = new XDocument();
            XElement element = null;
            try
            {
                switch (nodeType)
                {
                    case "XElement":
                        element = new XElement(name, name);
                        xDocument.Add(element);
                        IEnumerable<XNode> nodeList = xDocument.Nodes();
                        break;
                    case "XAttribute":
                        element = new XElement(name, name);
                        XAttribute attribute = new XAttribute(name, name);
                        element.Add(attribute);
                        xDocument.Add(element);
                        XAttribute x = element.Attribute(name);
                        break;
                    case "XName":
                        XName xName = XName.Get(name, name);
                        break;
                    default:
                        break;
                }
            }
            catch (XmlException)
            {
                return;
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.True(false, "Expected exception not thrown");
        }
Example #34
0
 /// <summary>
 /// Runs test for valid cases
 /// </summary>
 /// <param name="nodeType">XElement/XAttribute</param>
 /// <param name="name">name to be tested</param>
 public void RunValidTests(string nodeType, string name)
 {
     XDocument xDocument = new XDocument();
     XElement element = null;
     switch (nodeType)
     {
         case "XElement":
             element = new XElement(name, name);
             xDocument.Add(element);
             IEnumerable<XNode> nodeList = xDocument.Nodes();
             Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
             xDocument.RemoveNodes();
             break;
         case "XAttribute":
             element = new XElement(name, name);
             XAttribute attribute = new XAttribute(name, name);
             element.Add(attribute);
             xDocument.Add(element);
             XAttribute x = element.Attribute(name);
             Assert.Equal(name, x.Name.LocalName);
             xDocument.RemoveNodes();
             break;
         case "XName":
             XName xName = XName.Get(name, name);
             Assert.Equal(name, xName.LocalName);
             Assert.Equal(name, xName.NamespaceName);
             Assert.Equal(name, xName.Namespace.NamespaceName);
             break;
         default:
             break;
     }
 }