예제 #1
0
 public UcumReader(Stream stream)
 {
     document = XDocument.Load(stream);
     document.CreateNavigator();
     navigator = document.CreateNavigator();
     ns        = new XmlNamespaceManager(navigator.NameTable);
     ns.AddNamespace("u", "http://unitsofmeasure.org/ucum-essence");
 }
예제 #2
0
        public IEnumerable <Validation> Validations()
        {
            XPathNavigator nav = document.CreateNavigator();

            foreach (XPathNavigator n in nav.Select("ucumTests/validation/case"))
            {
                Validation validation = new Validation();
                validation.Id    = n.SelectSingleNode("@id").Value;
                validation.Unit  = n.SelectSingleNode("@unit").Value;
                validation.Valid = n.SelectSingleNode("@valid").Value == "true";
                //validation.Reason = = n.SelectSingleNode("unit").Value ;
                yield return(validation);
            }
        }
예제 #3
0
        public void saveTestCoreFunctionString()
        {
            document  = XDocument.Parse("<foo>hello<bar>world</bar><baz>how are you</baz></foo>");
            navigator = document.CreateNavigator();

            Assert.AreEqual("world", navigator.Evaluate("string(/foo/*)").ToString(), "#1");
            Assert.AreEqual("NaN", navigator.Evaluate("string(0 div 0)").ToString(), "#2");

            try
            {
                navigator.Evaluate("string(+0)");
                Assert.Fail("Expected an XPathException to be thrown.");
            }
            catch (XPathException) {}

            Assert.AreEqual("0", navigator.Evaluate("string(-0)").ToString(), "#3");
            Assert.AreEqual("Infinity", navigator.Evaluate("string(1 div 0)").ToString(), "#4");
            Assert.AreEqual("-Infinity", navigator.Evaluate("string(-1 div 0)").ToString(), "#5");
            Assert.AreEqual("45", navigator.Evaluate("string(45)").ToString(), "#6");
            Assert.AreEqual("-22", navigator.Evaluate("string(-22)").ToString(), "#7");
            Assert.AreEqual("0.25", navigator.Evaluate("string(.25)").ToString(), "#8");
            Assert.AreEqual("-0.25", navigator.Evaluate("string(-.25)").ToString(), "#9");
            Assert.AreEqual("2", navigator.Evaluate("string(2.0)").ToString(), "#10");
            Assert.AreEqual("2.01", navigator.Evaluate("string(2.01)").ToString(), "#11");
            Assert.AreEqual("-3", navigator.Evaluate("string(-3.0)").ToString(), "#12");
            Assert.AreEqual("3.45", navigator.Evaluate("string(3.45)").ToString(), "#13");

            // Wonder what this will look like under a different platform.
            Assert.AreEqual("0.33333333333333331", navigator.Evaluate("string(1 div 3)").ToString(), "#14");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
        /// </summary>
        /// <param name="documentPath">The physical path to XML document.</param>
        public XmlDocumentationProvider(string documentPath)
        {
            //if (documentPath == null)
            //{
            //    throw new ArgumentNullException("documentPath");
            //}
            //XPathDocument xpath = new XPathDocument(documentPath);
            //_documentNavigator = xpath.CreateNavigator();

            XDocument finalDoc = null;

            foreach (string file in Directory.GetFiles(HttpContext.Current.Server.MapPath("~/App_Code/"), "*.xml"))
            {
                if (finalDoc == null)
                {
                    finalDoc = XDocument.Load(File.OpenRead(file));
                }
                else
                {
                    XDocument xdocAdditional = XDocument.Load(File.OpenRead(file));

                    finalDoc.Root.XPathSelectElement("/doc/members")
                    .Add(xdocAdditional.Root.XPathSelectElement("/doc/members").Elements());
                }
            }

            // Supply the navigator that rest of the XmlDocumentationProvider code looks for
            _documentNavigator = finalDoc.CreateNavigator();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MultiXmlDocumentationProvider"/> class.
        /// </summary>
        /// <param name="documentPath">The physical path to XML document.</param>
        public MultiXmlDocumentationProvider(string xmlDocFilesPath)
        {
            XDocument finalDoc = null;

            foreach (string file in Directory.GetFiles(xmlDocFilesPath, "*.xml"))
            {
                using (var fileStream = File.OpenRead(file))
                {
                    if (finalDoc == null)
                    {
                        finalDoc = XDocument.Load(fileStream);
                    }
                    else
                    {
                        XDocument xdocAdditional = XDocument.Load(fileStream);

                        finalDoc.Root.XPathSelectElement("/doc/members")
                        .Add(xdocAdditional.Root.XPathSelectElement("/doc/members").Elements());
                    }
                }
            }

            // Supply the navigator that rest of the XmlDocumentationProvider code looks for
            _documentNavigator = finalDoc.CreateNavigator();
        }
        /// <summary>
        /// Transforms an XDocument to a new XDocument file using an embedded resource xslt file
        /// </summary>
        /// <param name="inputXDoc">XDocument to be transformed to KML</param>
        /// <param name="xsltFileName">Name of .xslt file in Resources folder (must be Embedded Resource)</param>
        /// <returns>new XDocument</returns>
        private static XDocument TransformXDocumentWithResourcesXslt(XDocument inputXDoc, string xsltFileName)
        {
            XslCompiledTransform xslt     = new XslCompiledTransform();
            XsltSettings         settings = new XsltSettings(true, false);

            XmlWriterSettings writerSettings = new XmlWriterSettings();

            writerSettings.Indent      = true;
            writerSettings.IndentChars = "\t";
            writerSettings.Encoding    = Encoding.UTF8;

            StringBuilder outputXmlStringBuilder = new StringBuilder();
            XmlWriter     xmlWriter = XmlWriter.Create(outputXmlStringBuilder, writerSettings);

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream xsltFileStream = assembly.GetManifestResourceStream("RunningAhead2Kml.Resources." + xsltFileName))
            {
                using (XmlReader reader = XmlReader.Create(xsltFileStream))
                {
                    xslt.Load(reader, settings, new XmlUrlResolver());
                    xslt.Transform(inputXDoc.CreateNavigator(), xmlWriter);
                }
            }
            XDocument newDoc = XDocument.Parse(outputXmlStringBuilder.ToString());

            return(newDoc);
        }
예제 #7
0
        public static bool UpdateXmlResource(string res, string filename, Dictionary <string, string> acwMap, IEnumerable <string> additionalDirectories = null, Action <TraceLevel, string> logMessage = null, Action <string, string> registerCustomView = null)
        {
            // use a temporary file so we only update the real file if things actually changed
            string tmpfile = filename + ".bk";

            try {
                XDocument doc = XDocument.Load(filename, LoadOptions.SetLineInfo);
                UpdateXmlResource(res, doc.Root, acwMap, additionalDirectories, logMessage, (e) => {
                    registerCustomView?.Invoke(e, filename);
                });
                using (var stream = File.OpenWrite(tmpfile))
                    using (var xw = new LinePreservedXmlWriter(new StreamWriter(stream)))
                        xw.WriteNode(doc.CreateNavigator(), false);

                return(Xamarin.Android.Tasks.MonoAndroidHelper.CopyIfChanged(tmpfile, filename));
            } catch (Exception e) {
                logMessage?.Invoke(TraceLevel.Warning, $"AndroidResgen: Warning while updating Resource XML '{filename}': {e.Message}");
                return(false);
            } finally {
                if (File.Exists(tmpfile))
                {
                    File.Delete(tmpfile);
                }
            }
        }
예제 #8
0
        public void CopiesComplexContent()
        {
            var dom     = new XDocument();
            var content =
                new TextOf(
                    "<?xml version=\"1.0\" encoding=\"utf-16\"?>"
                    + "<?some-pi test?>"
                    + "<target id=\"BBA3CBB0-00F0-43DD-9F74-87C53D35270C\" name=\"j1046rfa_11\">"
                    + "<body><accessibility><readonly>false</readonly><reason /></accessibility><type>default</type><spatials><cartesian machine=\"BEFC5DE8-C579-44A6-ACDF-65293C39C87F\"><translation x=\"-4150.784755\" y=\"-1819.545936\" z=\"955.4282165\" /><rotation rx=\"-2.949491294\" ry=\"-0.8920227643\" rz=\"-3.120333533\" /><configuration><joints><joint name=\"j1\" state=\"irrelevant\"><turn hasvalue=\"true\">0</turn></joint><joint name=\"j2\" state=\"irrelevant\"><turn hasvalue=\"false\">0</turn></joint><joint name=\"j3\" state=\"negative\"><turn hasvalue=\"false\">0</turn></joint><joint name =\"j4\" state=\"irrelevant\"><turn hasvalue=\"true\">0</turn></joint><joint name=\"j5\" state=\"positive\"><turn hasvalue=\"false\">0</turn></joint><joint name=\"j6\" state=\"irrelevant\"><turn hasvalue=\"true\">0</turn></joint></joints><overhead>negative</overhead></configuration></cartesian><axial machine=\"F399FDD7-B9FF-4D5F-8A65-C5EC35D306BE\"><axes><axis name=\"j1\">-4871</axis></axes></axial></spatials><parameters><motiontype>ptp</motiontype><speed>70</speed><acceleration>100</acceleration><zone>C_DIS</zone><referenceframe>b4</referenceframe><toolframe>t2</toolframe><storagetype>local</storagetype><processtype /></parameters><postolpcommands /></body><foot /></target>"
                    );
            var xml = XDocument.Parse(content.AsString());

            new Xambler(
                new Joined <IDirective>(
                    new ManyOf <IDirective>(
                        new AddDirective("target")
                        ),
                    new CopyOfDirective(xml.Root.Element("body"))
                    )
                ).Apply(dom);

            var nav = dom.CreateNavigator();

            Assert.True(
                nav.SelectSingleNode("/target/body/accessibility/readonly").Value == "false"
                );
        }
예제 #9
0
        private TripleSlashCommentModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
        {
            // Transform triple slash comment
            XDocument doc = TripleSlashCommentTransformer.Transform(xml, language);

            _context = context;
            if (!context.PreserveRawInlineComments)
            {
                ResolveSeeCref(doc, context.AddReferenceDelegate, context.ResolveCRef);
                ResolveSeeAlsoCref(doc, context.AddReferenceDelegate, context.ResolveCRef);
                ResolveExceptionCref(doc, context.AddReferenceDelegate, context.ResolveCRef);
            }
            ResolveCodeSource(doc, context);
            var nav = doc.CreateNavigator();

            Summary = GetSummary(nav, context);
            Remarks = GetRemarks(nav, context);
            Returns = GetReturns(nav, context);

            Exceptions     = GetExceptions(nav, context);
            Sees           = GetSees(nav, context);
            SeeAlsos       = GetSeeAlsos(nav, context);
            Examples       = GetExamples(nav, context);
            Parameters     = GetParameters(nav, context);
            TypeParameters = GetTypeParameters(nav, context);
            IsInheritDoc   = GetIsInheritDoc(nav, context);
        }
        public static IDictionary <string, string> GetSchemasInFile(XDocument doc)
        {
            XPathNavigator nav = doc.CreateNavigator();

            nav.MoveToFollowing(XPathNodeType.Element);
            return(nav.GetNamespacesInScope(XmlNamespaceScope.All));
        }
예제 #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
        /// </summary>
        /// <param name="documentPath">The physical path to XML document.</param>
        public MultiXmlDocumentationProvider(string appDataPath, string fileWildCard)
        {
            if (appDataPath == null)
            {
                throw new ArgumentNullException("documentPath");
            }
            XDocument finalDoc = null;

            foreach (var file in Directory.GetFiles(appDataPath, fileWildCard))
            {
                using (var fileStream = File.OpenRead(file))
                {
                    if (finalDoc == null)
                    {
                        finalDoc = XDocument.Load(fileStream);
                    }
                    else
                    {
                        var xdocAdditional = XDocument.Load(fileStream);
                        finalDoc.Root.XPathSelectElement("/doc/members").Add(xdocAdditional.Root.XPathSelectElement("/doc/members").Elements());
                    }
                }
            }
            // Supply the navigator that rest of the XmlDocumentationProvider code looks for
            this._documentNavigator = finalDoc.CreateNavigator();
        }
        public XPathNavigator CreateNavigator(string xml)
        {
            TextReader sr        = new StringReader(xml);
            XDocument  xDocument = XDocument.Load(sr, LoadOptions.PreserveWhitespace);

            return(xDocument.CreateNavigator());
        }
예제 #13
0
        public static void UpdateXmlResource(string filename, Dictionary <string, string> acwMap, IEnumerable <string> additionalDirectories = null)
        {
            // use a temporary file so we only update the real file if things actually changed
            string tmpfile = filename + ".bk";

            try {
                XDocument doc = XDocument.Load(filename, LoadOptions.SetLineInfo);

                // The assumption here is that the file we're fixing up is in a directory below the
                // obj/${Configuration}/res/ directory and so appending ../gives us the actual path to
                // 'res/'
                UpdateXmlResource(Path.Combine(Path.GetDirectoryName(filename), ".."), doc.Root, acwMap, additionalDirectories);
                using (var stream = File.OpenWrite(tmpfile))
                    using (var xw = new LinePreservedXmlWriter(new StreamWriter(stream)))
                        xw.WriteNode(doc.CreateNavigator(), false);
                Xamarin.Android.Tasks.MonoAndroidHelper.CopyIfChanged(tmpfile, filename);
                File.Delete(tmpfile);
            }
            catch (Exception e) {
                if (File.Exists(tmpfile))
                {
                    File.Delete(tmpfile);
                }
                Console.Error.WriteLine("AndroidResgen: Warning while updating Resource XML '{0}': {1}", filename, e.Message);
                return;
            }
        }
        public XPathNavigator CreateNavigatorFromFile(string fileName)
        {
            Stream    stream    = FileHelper.CreateStreamFromFile(fileName);
            XDocument xDocument = XDocument.Load(stream, LoadOptions.PreserveWhitespace);

            return(xDocument.CreateNavigator());
        }
예제 #15
0
        private void LoadPortFromJellyfinConfig()
        {
            try
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\Jellyfin\\Server");
                // registry keys are probably written by a 32bit installer, so check the 32bit registry folder
                if (registryKey == null)
                {
                    registryKey = Registry.LocalMachine.OpenSubKey("Software\\WOW6432Node\\Jellyfin\\Server");
                }
                _installFolder = registryKey.GetValue("InstallFolder").ToString();
                _dataFolder    = registryKey.GetValue("DataFolder").ToString();
                _configFile    = Path.Combine(_dataFolder, "config\\system.xml").ToString();


                if (File.Exists(_configFile))
                {
                    XDocument      systemXml      = XDocument.Load(_configFile);
                    XPathNavigator SettingsReader = systemXml.CreateNavigator();

                    FirstRunDone = SettingsReader.SelectSingleNode("/ServerConfiguration/IsStartupWizardCompleted").ValueAsBoolean;
                    string port = SettingsReader.SelectSingleNode("/ServerConfiguration/PublicPort").Value;

                    _localJellyfinUrl = "http://localhost:" + port + "/web/index.html";
                }
            }
            catch (Exception ex)
            {
                // We could not get the Jellyfin port from system.xml config file - just use default?
                MessageBox.Show("Error: " + ex.Message + "\r\nCouldn't load configuration. The application will now close.");
                Application.Exit();
                return;
            }
        }
예제 #16
0
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns>
        /// Returns an XML structure of the search results.
        /// </returns>
        private static XPathNodeIterator GetResultsAsXml(IEnumerable <SearchResult> results)
        {
            var attributes = new List <string> {
                "id", "nodeName", "updateDate", "writerName", "path", "nodeTypeAlias", "parentID", "loginName", "email"
            };

            XDocument doc = new XDocument();

            if (results.Count() > 0)
            {
                XElement nodes = new XElement("results");
                foreach (SearchResult result in results)
                {
                    XElement node = new XElement(result.Fields["nodeTypeAlias"]);
                    node.Add(new object[] { new XAttribute("score", result.Score) });

                    foreach (KeyValuePair <string, string> item in result.Fields)
                    {
                        // if the field key starts with '__' (double-underscore) - then skip.
                        if (item.Key.StartsWith("__"))
                        {
                            continue;
                        }
                        // if not legacy schema and 'nodeTypeAlias' - add the @isDoc attribute
                        if (item.Key == "nodeTypeAlias")
                        {
                            node.Add(new object[] { new XAttribute("isDoc", string.Empty) });
                        }
                        // check if the field is an attribute or a data value
                        else if (attributes.Contains(item.Key))
                        {
                            // attribute field
                            node.Add(new object[] { new XAttribute(item.Key, item.Value) });
                        }
                        else
                        {
                            // data field
                            XElement data = new XElement(item.Key);

                            // CDATA the value - because we don't know what it is!
                            data.Add(new object[] { new XCData(item.Value) });

                            // add the data field to the node.
                            node.Add(data);
                        }
                    }

                    // add the node to the collection.
                    nodes.Add(node);
                }

                doc.Add(nodes);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return(doc.CreateNavigator().Select("/*"));
        }
예제 #17
0
        private TripleSlashCommentModel(string xml, ITripleSlashCommentParserContext context)
        {
            // Normalize xml line ending before load into xml
            XDocument doc = XDocument.Parse(xml, LoadOptions.SetLineInfo | LoadOptions.PreserveWhitespace);

            if (!context.PreserveRawInlineComments)
            {
                ResolveSeeCref(doc, context.AddReferenceDelegate);
                ResolveSeeAlsoCref(doc, context.AddReferenceDelegate);
                ResolveParameterRef(doc);
            }
            var nav = doc.CreateNavigator();

            _lines  = doc.ToString().Split('\n');
            Summary = GetSummary(nav, context);
            Remarks = GetRemarks(nav, context);
            Returns = GetReturns(nav, context);

            Exceptions     = GetExceptions(nav, context);
            Sees           = GetSees(nav, context);
            SeeAlsos       = GetSeeAlsos(nav, context);
            Examples       = GetExamples(nav, context);
            Parameters     = GetParameters(nav, context);
            TypeParameters = GetTypeParameters(nav, context);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
        /// </summary>
        /// <param name="documentPath">The physical path to XML document.</param>
        public XmlDocumentationProvider(string documentPath)
        {
            /*if (documentPath == null)
             * {
             *  throw new ArgumentNullException("documentPath");
             * }
             * XPathDocument xpath = new XPathDocument(documentPath);
             * _documentNavigator = xpath.CreateNavigator();*/

            XDocument finalDoc = null;

            foreach (string file in Directory.GetFiles(documentPath, "*.xml"))
            {
                if (finalDoc == null)
                {
                    finalDoc = XDocument.Load(File.OpenRead(file));
                }
                else
                {
                    XDocument xdocAdditional = XDocument.Load(File.OpenRead(file));
                    finalDoc.Root.XPathSelectElement("/doc/members")
                    .Add(xdocAdditional.Root.XPathSelectElement("/doc/members").Elements());
                }
            }
            // Supply the navigator that rest of the XmlDocumentationProvider code looks for
            _documentNavigator = finalDoc.CreateNavigator();
        }
예제 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
        /// </summary>
        /// <param name="documentPath">The physical path to XML document.</param>
        public XmlDocumentationProvider(string documentPath, string fileName)
        {
            if (documentPath == null)
            {
                throw new ArgumentNullException("documentPath");
            }


            XDocument finalDoc = null;

            foreach (string file in Directory.GetFiles(documentPath, "*.xml"))
            {
                using (var fileStream = File.OpenRead(file))
                {
                    if (finalDoc == null)
                    {
                        finalDoc = XDocument.Load(fileStream);
                    }
                    else
                    {
                        XDocument xdocAdditional = XDocument.Load(fileStream);

                        finalDoc.Root.XPathSelectElement("/doc/members")
                        .Add(xdocAdditional.Root.XPathSelectElement("/doc/members").Elements());
                    }
                }
            }
            finalDoc = XDocument.Parse(finalDoc.ToString().Replace("`1", ""));

            _documentNavigator = finalDoc.CreateNavigator();
            // finalDoc.Save(documentPath+fileName);
        }
예제 #20
0
        public static string GetUsername(ConsumerBase twitter, string accessToken)
        {
            XDocument      xml = VerifyCredentials(twitter, accessToken);
            XPathNavigator nav = xml.CreateNavigator();

            return(nav.SelectSingleNode("/user/screen_name").Value);
        }
        public void Execute(XDocument document)
        {
            var navigator        = document.CreateNavigator();
            var namespaceManager = new XmlNamespaceManager(new NameTable());

            namespaceManager.AddNamespace("x", document.Root.Name.NamespaceName);

            // unfortunately evaluating
            var enumerable = (IEnumerable <object>)document.XPathEvaluate(Path, namespaceManager);
            var node       = enumerable.FirstOrDefault() as XObject;

            if (node is XElement)
            {
                ((XElement)node).Remove();
            }
            else if (node is XAttribute)
            {
                var att           = (XAttribute)node;
                var parent        = att.Parent;
                var newAttributes = parent.Attributes().Except(new[] { att });
                parent.RemoveAttributes();
                parent.Add(newAttributes);
            }
            else
            {
                throw new Exception("Unable to find element via XPath.");
            }
        }
        /// <summary>
        /// Get the result for the GeoLocate service call.
        /// The document parameter is the result from the service call, which is assumed
        /// to be an XML structure
        /// </summary>
        protected override IList <WebGeoLocatorResultAddress> GetGeoLocateServiceResult(XDocument document)
        {
            var result = new List <WebGeoLocatorResultAddress>();

            if (document != null)
            {
                var navi = document.CreateNavigator();
                var iter = navi.SelectDescendants("place", string.Empty, false);

                while (iter.MoveNext())
                {
                    var name = iter.Current.GetAttribute("display_name", string.Empty);
                    var bb   = iter.Current.GetAttribute("boundingbox", string.Empty);

                    if (!String.IsNullOrEmpty(bb) && !String.IsNullOrEmpty(name))
                    {
                        var coords = GetDoublesFromString(bb);

                        if (coords.Count == 4)
                        {
                            var env = CreateWGS84Envelope(coords[2], coords[0], coords[3], coords[1]);

                            if (env != null)
                            {
                                result.Add(new WebGeoLocatorResultAddress {
                                    Name = name, Bounds = env
                                });
                            }
                        }
                    }
                }
            }

            return(result);
        }
예제 #23
0
 /// <summary>
 /// Creates a new instance of the ValidationEvaluator containing the
 /// the validation schema and a specific XML document to be validated.
 /// </summary>
 /// <param name="schema">Validation schema. Must not be null.</param>
 /// <param name="xInstance">An instance of an XML document to be validated.
 /// Must not be null.</param>
 /// <param name="fullValidation">Indicates whether to validate the
 /// whole document regardless of any assertion, or to stop validation at
 /// the first assertion.</param>
 public ValidationEvaluator(Schema schema, XDocument xInstance, bool fullValidation)
 {
     this.schema         = schema;
     this.xInstance      = xInstance;
     this.fullValidation = fullValidation;
     this.xNavigator     = xInstance.CreateNavigator();
 }
        static void Main(string[] args)
        {
            string              xml = @"
    <body>
        <par id = ""1"">
          <prop type=""Content"">One</prop>
          <child xml:id=""1"">
            <span>This is span 1</span>
          </child>
          <child xml:id=""2"">
            <span>This is span 2</span>
          </child>
        </par>
    </body>";
            XDocument           doc = XDocument.Parse(xml);
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.CreateNavigator().NameTable);

            namespaceManager.AddNamespace("xml", "http://www.w3.org/XML/1998/namespace");
            XElement span1 = doc.Root.XPathSelectElement(@"/body/par/child[@xml:id = ""1""]/span[1]", namespaceManager);
            XElement span2 = doc.Root.XPathSelectElement(@"/body/par/child[@xml:id = ""2""]/span[1]", namespaceManager);

            span1.ReplaceWith(span2);
            span2.ReplaceWith(span1);

            Console.WriteLine(doc);
        }
예제 #25
0
        public XmlNamespaceManagerEnhanced(XDocument doc)
            : base(doc.CreateReader().NameTable)
        {
            var ns = doc.Root.GetDefaultNamespace();

            if (ns != null && !string.IsNullOrWhiteSpace(ns.NamespaceName))
            {
                this.defaultNamespace = ns.NamespaceName;
                AddNamespace(Common.DefaultNamespace, this.defaultNamespace);
            }

            var nslist = new Dictionary <string, string>();
            var nav    = doc.CreateNavigator();

            while (nav.MoveToFollowing(XPathNodeType.Element))
            {
                var newFoundNapespaces = nav.GetNamespacesInScope(XmlNamespaceScope.All).Where(a => !nslist.ContainsKey(a.Key) && !this.HasNamespace(a.Key));
                foreach (var item in newFoundNapespaces)
                {
                    nslist.Add(item.Key, item.Value);
                }
            }

            foreach (var item in nslist)
            {
                if (string.IsNullOrWhiteSpace(item.Key))
                {
                    continue;
                }
                AddNamespace(item.Key, item.Value);
            }
        }
예제 #26
0
            bool TraceExceptionXml(Exception exception, string format, params object[] args)
            {
                if (source.Listeners.OfType <XmlWriterTraceListener> ().Any())
                {
                    var message = format;
                    if (args != null && args.Length > 0)
                    {
                        message = string.Format(CultureInfo.CurrentCulture, format, args);
                    }

                    var xdoc   = new XDocument();
                    var writer = xdoc.CreateWriter();

                    writer.WriteStartElement("", "TraceRecord", TraceXmlNs);
                    writer.WriteAttributeString("Severity", "Error");
                    //writer.WriteElementString ("TraceIdentifier", msdnTraceCode);
                    writer.WriteElementString("Description", TraceXmlNs, message);
                    writer.WriteElementString("AppDomain", TraceXmlNs, AppDomain.CurrentDomain.FriendlyName);
                    writer.WriteElementString("Source", TraceXmlNs, source.Name);
                    AddExceptionXml(writer, exception);
                    writer.WriteEndElement();

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

                    source.TraceData(TraceEventType.Error, 0, xdoc.CreateNavigator());
                    return(true);
                }

                return(false);
            }
예제 #27
0
        /// <summary>
        /// transform the POS that has templates to GAFAWS format
        /// </summary>
        private void TransformPosInfoToGafawsInputFormat(XElement templateElem, string gafawsFile)
        {
            var dom = new XDocument(new XElement(templateElem));

            using (var writer = new StreamWriter(Path.Combine(Path.GetTempPath(), gafawsFile)))
                GafawsTransform.Transform(dom.CreateNavigator(), null, writer);
        }
        /// <summary>
        /// выполнить конвертацию структуры
        /// </summary>
        public void Do()
        {
            try
            {
                SendMessage("\n- Конвертация структуры курса");
                XDocument doc = new XDocument(course);
                doc.Document.Declaration = new XDeclaration("1.0", "utf-8", "true");
                XPathNavigator nv = doc.CreateNavigator();

                XslCompiledTransform xslt = new XslCompiledTransform();

                xslt.Load(convParams.ContentShemePath);

                XsltArgumentList xslArg = new XsltArgumentList();
                xslArg.AddParam("itemsPath", "", convParams.RootFolderName);

                string outFile = Path.Combine(convParams.OutputAbsPath, convParams.StartFileName);

                using (FileStream fs = new FileStream(outFile, FileMode.Create))
                {
                    xslt.Transform(nv, xslArg, fs);
                }
            }
            catch (Exception ex)
            {
                LastError = ex.Message;
                throw new Exception("Исключение при конвертации структуры курса: " + ex.Message);
            }
        }
        internal static void XPathNavigator()
        {
            XDocument      rss          = XDocument.Load("https://weblogs.asp.net/dixin/rss");
            XPathNavigator rssNavigator = rss.CreateNavigator();

            rssNavigator.NodeType.WriteLine();           // Root
            rssNavigator.MoveToFirstChild().WriteLine(); // True
            rssNavigator.Name.WriteLine();               // rss

            ((XPathNodeIterator)rssNavigator
             .Evaluate("/rss/channel/item[guid/@isPermaLink='true']/category"))
            .Cast <XPathNavigator>()
            .Select(categoryNavigator => categoryNavigator.UnderlyingObject)
            .Cast <XElement>()
            .GroupBy(
                category => category.Value,     // Current text node's value.
                category => category,
                (key, group) => new { Name = key, Count = group.Count() },
                StringComparer.OrdinalIgnoreCase)
            .OrderByDescending(category => category.Count)
            .Take(5)
            .Select(category => $"[{category.Name}]:{category.Count}")
            .WriteLines();
            // [C#]:9 [LINQ]:6 [.NET]:5 [Functional Programming]:4 [LINQ via C#]:4
        }
예제 #30
0
        /// <summary>
        /// Get username.
        /// </summary>
        /// <param name="accessToken">The access token</param>
        /// <returns>Theusername.</returns>
        public string GetUsername(IToken accessToken)
        {
            XDocument      xml = VerifyCredentials(accessToken);
            XPathNavigator nav = xml.CreateNavigator();

            return(nav.SelectSingleNode("/user/screen_name").Value);
        }