コード例 #1
0
		// Creates the dynamic content from the twitter results
		RootElement CreateDynamicContent (XDocument doc)
		{
			var users = doc.XPathSelectElements ("./statuses/status/user").ToArray ();
			var texts = doc.XPathSelectElements ("./statuses/status/text").Select (x=>x.Value).ToArray ();
			var people = doc.XPathSelectElements ("./statuses/status/user/name").Select (x=>x.Value).ToArray ();
			
			var section = new Section ();
			var root = new RootElement ("Tweets") { section };
			
			for (int i = 0; i < people.Length; i++){
				var line = new RootElement (people [i]) { 
					new Section ("Profile"){
						new StringElement ("Screen name", users [i].XPathSelectElement ("./screen_name").Value),
						new StringElement ("Name", people [i]),
						new StringElement ("oFllowers:", users [i].XPathSelectElement ("./followers_count").Value)
					},
					new Section ("Tweet"){
						new StringElement (texts [i])
					}
				};
				section.Add (line);
			}
			
			return root;
		}
コード例 #2
0
        public XDocument TransformOutput(XDocument output)
        {
            var elements = output.XPathSelectElements("//jetbrains.buildServer.messages.BuildMessage1"
                                                      + "[./myTypeId[text()='BlockStart'] and "
                                                      + ".//blockType[text() ='$TEST_BLOCK$']]");

            var tests = elements.Select(x => new TestResult 
            { 
                FullName = x.XPathSelectElement(".//blockName").Value, 
                RunTime = long.Parse(x.XPathSelectElement(".//myTimestamp").Value),
                Succeeded = x.NextNode.XPathSelectElement(".//myTypeId").Value != "TestFailure"
            })
            .OrderBy(x => x.RunTime);

            var testsToRemove = from testResult in tests.GroupBy(x => x.FullName)
                where testResult.Any(x => x.Succeeded)
                select testResult.Key;

            foreach (var testToRemove in testsToRemove)
            {
                output.XPathSelectElements(
                    "//jetbrains.buildServer.messages.BuildMessage1[./myTypeId[text()='TestFailure'] and .//testName[text()='"
                    + testToRemove + "']]").Remove();
            }

            return output;
        }
コード例 #3
0
ファイル: IBArchive.cs プロジェクト: smartmobili/CocoaBuilder
        public static IBArchive Parse(XDocument xDoc)
        {
            IBArchive ibArchive = new IBArchive();

            foreach (XAttribute attr in xDoc.Root.Attributes())
            {
                if (attr.Name == "type")
                    ibArchive.Type = attr.Value;
                if (attr.Name == "version")
                    ibArchive.Version = attr.Value;
            }

            var elements = xDoc.XPathSelectElements(@"/archive/data/*");
            foreach (var element in elements)
            {
                var key = element.Attributes().Where(attr => attr.Name == "key").FirstOrDefault();
                if (key != null && element.Attribute("key").Value.StartsWith("IBDocument."))
                {
                    //IBDocument.Parse(ibArchive.Data, element);
                }
            }

            //if (xmlReader.Name == "archive")
            //{
            //    while (xmlReader.MoveToNextAttribute())
            //    {
            //        if (xmlReader.Name == "type")
            //            ibArchive.Type = xmlReader.Value;
            //        else if (xmlReader.Name == "version")
            //            ibArchive.Version = xmlReader.Value;
            //    }
            //}

            return ibArchive;
        }
コード例 #4
0
 private static void TraverseXmlDocument(XDocument doc)
 {
     foreach (var leagueElement in doc.XPathSelectElements("leagues-and-teams/league"))
     {
         AddLeague(leagueElement);
     }
 }
コード例 #5
0
ファイル: ReportsMenu.cs プロジェクト: stevesloka/bvcms
        private static string ReportItems(XDocument xdoc, string path)
        {
            var sb = new StringBuilder();
            foreach (var e in xdoc.XPathSelectElements(path).Elements())
            {
                var roles = ((string)e.Attribute("roles"))?.Split(',');
                if (roles != null)
                    if (!roles.Any(rr => DbUtil.Db.CurrentUser.Roles.Contains(rr)))
                        continue;

                var tb = new TagBuilder("li");
                switch (e.Name.LocalName)
                {
                    case "Report":
                        var a = new TagBuilder("a");
                        a.MergeAttribute("href", e.Attribute("link").Value);
                        var t = e.Attribute("target");
                        if (t != null)
                            a.MergeAttribute("target", t.Value);
                        a.SetInnerText(e.Value);
                        tb.InnerHtml = a.ToString();
                        break;
                    case "Header":
                        tb.AddCssClass("dropdown-header");
                        tb.SetInnerText(e.Value);
                        break;
                    case "Space":
                        tb.AddCssClass("divider");
                        break;
                }
                sb.AppendLine(tb.ToString());
            }
            return sb.ToString();
        }
コード例 #6
0
 public virtual bool Transform(XDocument document)
 {
     if (document == null) { return false; }
     var elementArray = document.XPathSelectElements(this.Xpath).ToArray<XElement>();
     if (elementArray.Length == 0) { return false; }
     var changeMade = false;
     foreach (var element in elementArray)
     {
         var attribute = element.Attribute(this.AttributeName);
         if (attribute == null) { continue; }
         string newValue = null;
         if (this.ChangeType == AttributeValueChangeType.Replace)
         {
             newValue = this.NewValue;
         }
         else if (this.ChangeType == AttributeValueChangeType.Prepend)
         {
             newValue = this.NewValue + attribute.Value;
         }
         else if (this.ChangeType == AttributeValueChangeType.Append)
         {
             newValue = attribute.Value + this.NewValue;
         }
         if (!string.IsNullOrEmpty(newValue) && ! newValue.Equals(attribute.Value))
         {
             attribute.Value = newValue;
             changeMade = true;
         }
     }
     return changeMade;
 }
コード例 #7
0
        private XDocument GetContentByXPath(string xpath, XDocument content)
        {
            var xdoc = XDocument.Parse("<content></content>");
            xdoc.Root.Add(content.XPathSelectElements(xpath));

            return xdoc;
        }
コード例 #8
0
        static void Main()
        {
            string documentPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\expenses.xml";
            var xmlDocument = new XDocument();
            try
            {
                xmlDocument = XDocument.Load(documentPath);
                Console.WriteLine("XML file has been found!");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("File not found!");
            }

            var nodes = xmlDocument.XPathSelectElements("//expenses-by-month/vendor");

            foreach (var vendor in nodes)
            {
                string vendorName = vendor.Attribute("name").Value;
                var expenses = vendor.Elements("expenses");

                foreach (var expense in expenses)
                {
                    DateTime month = DateTime.Parse(expense.Attribute("month").Value);
                    decimal amount = decimal.Parse(expense.Value);
                    AddVendorExpense(vendorName, month, amount);
                }
            }
        }
コード例 #9
0
 public static string ExtractUriFromLink(string relEndsWith, XDocument xml, XmlNamespaceManager namespaceManager)
 {
     return xml
         .XPathSelectElements("//dp:link/dp:rel", namespaceManager)
         .Where(element => element.Value.EndsWith(relEndsWith))
         .First()
         .XPathSelectElement("../dp:uri", namespaceManager)
         .Value;
 }
コード例 #10
0
 private static void AddReferencesFromProject(DependencyGraphBuilder builder, object proj, XDocument xproject, string projectFile,
     HashSet<string> referencedProjects)
 {
     foreach (var xtarget in xproject.XPathSelectElements("/projectDescription/projects/project"))
     {
         var targetProjectName = xtarget.Value;
         if (!referencedProjects.Contains(targetProjectName))
             builder.AddProjectReference(proj, targetProjectName, null, null, null, ToLocation(projectFile, xtarget), null);
     }
 }
コード例 #11
0
ファイル: XPathEngine.cs プロジェクト: Waltervondehans/NBi
        public NBi.Core.ResultSet.ResultSet Execute(XDocument items)
        {
            var result = from item in items.XPathSelectElements(@from)
                         select GetObj(item);

            var builder = new ResultSetBuilder();
            var rows = result.ToArray();
            var resultSet = builder.Build(rows);
            return resultSet;
        }
コード例 #12
0
ファイル: search.cs プロジェクト: GuojunSu/RestMedical
    public int ProcessXML(XDocument file,string userid)
    {
        string level;
        SqlCommand sqlCmd1;
        SqlDataReader read1;
        SqlConnection sqlCon = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        sqlCon.Open();

        if (userid == null)
            userid = "PatientFolder";
        string FolderPath = @"D:\C sharp code\LongTermCare(Xml)\Search\Query_Xml\" + userid;
        DirectoryInfo DIFO = new DirectoryInfo(FolderPath);//判斷資料夾存在否
        if (!DIFO.Exists)
        {
            DIFO.Create();
        }

        level = file.Root.Name.ToString();
        IEnumerable<XElement> list1 = file.XPathSelectElements(level);//root node
        int Querycount = 0;
        foreach (XElement item in list1.Elements())
        {//get fieldname and value
            if (item.Value.ToString() != "")
            {
                QFieldName[Querycount] = item.Attribute("FieldName").Value.ToString().Replace(" ", "");
                QVR[Querycount] = item.Attribute("VR").Value.ToString();
                Qvalue[Querycount++] = item.Value.ToString();
            }
        }
        int checkwhere = 0;
        for (int i = 0; i < Querycount; i++)//saerch tablename then combine SQL
        {
            sqlCmd1 = new SqlCommand("select DISTINCT TableName from TableFields where FieldName='" + QFieldName[i] + "'", sqlCon);
            read1 = sqlCmd1.ExecuteReader();
            read1.Read();
            if (Qvalue[i] != "*")
            {
                if (++checkwhere == 1)
                    Terms = "where" + ' ' + Terms;
                Terms += read1["TableName"].ToString() + "." + QFieldName[i];
                if ((QVR[i] == "DA" || QVR[i] == "TM") && Qvalue[i].Length == 9)
                    Terms += Qvalue[i];
                else if ((QVR[i] == "DA" || QVR[i] == "TM") && Qvalue[i].Length > 9)
                {
                    string[] strs = Qvalue[i].Split('-');
                    Terms += ">" + strs[0] + " and " + read1["TableName"].ToString() + "." + QFieldName[i] + "<" + strs[1];
                }
                else
                    Terms += "=" + "'" + Qvalue[i] + "'";
                if (i < Querycount - 1)
                    Terms += ' ' + "and ";
            }
        }
        return Query(level, userid);
    }
コード例 #13
0
ファイル: Preprocessor.cs プロジェクト: xpekatt/SchemaTron
        /// <summary>
        /// Resolves all abstract patterns in the schema by replacing
        /// parameter references by actual parameter values in all enclosed
        /// attributes that contain queries.
        /// </summary>
        /// <param name="xSchema">Validation schema</param>
        /// <param name="nsManager">Namespace manager</param>
        /// <exception cref="ArgumentNullException" />
        public static void ResolveAbstractPatterns(XDocument xSchema, XmlNamespaceManager nsManager)
        {
            if (xSchema == null)
            {
                throw new ArgumentNullException("xSchema");
            }

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

            // select abstract patterns
            Dictionary<string, XElement> dicAPs = new Dictionary<string, XElement>();
            foreach (XElement xAbstractPattern in xSchema.XPathSelectElements("//sch:pattern[@abstract='true']", nsManager))
            {
                string id = xAbstractPattern.Attribute(XName.Get("id")).Value;
                dicAPs.Add(id, xAbstractPattern);
            }

            if (dicAPs.Count > 0)
            {
                // select instances
                List<XElement> listInstances = new List<XElement>();
                foreach (XElement xInstance in xSchema.XPathSelectElements("//sch:pattern[@is-a]", nsManager))
                {
                    listInstances.Add(xInstance);
                }

                // replace instances
                foreach (XElement xInstance in listInstances)
                {
                    ReplaceAbstractPatternInstance(dicAPs, xInstance, nsManager);
                }

                // remove abstract patterns
                foreach (KeyValuePair<string, XElement> item in dicAPs)
                {
                    item.Value.Remove();
                }
            }
        }
コード例 #14
0
ファイル: MainWindow.xaml.cs プロジェクト: g8605/IIO11300
        public MainWindow()
        {
            InitializeComponent();
            try
            {   
                // app.configista löytyvä viinit1.xml
                string wines = ConfigurationManager.AppSettings.Get("XMLFile");
                //ladataan xml-tiedosto
                doc = XDocument.Load(wines);
                
                //säätöä
                /**var query = from w in doc.Descendants("wine")
                            select new {
                                //nimi = w.Element("nimi").Value,
                                maa = w.Element("maa").Value,
                                //arvio = w.Element("arvio").Value
                            }; **/
                
               // maat comboboxiin
                foreach (var elem in doc.XPathSelectElements("//maa"))
                {                    
                    if (!cmbValinta.Items.Contains(elem.Value))
                    {
                        cmbValinta.Items.Add(elem.Value);
                    }
                 
                }
                
                // kaikki vinetot datagridiin
                foreach (var elem in doc.XPathSelectElements("//wine"))
                {
                    dgViinit.Items.Add(elem).ToString();

                }
                cmbValinta.Items.Add("Kaikki vinetot");
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erroria: " + ex.Message);
            }
        }               
コード例 #15
0
 public XmlNamespaceHelper(XDocument xml, string defaultPrefix)
 {
     DefaultPrefix    = defaultPrefix;
     NamespaceManager = new XmlNamespaceManager(new NameTable());
     xml.XPathSelectElements("//*").SelectMany(e => e.Attributes())
     .Where(a => a.IsNamespaceDeclaration)
     .GroupBy(a => a.Name.Namespace == XNamespace.None ? defaultPrefix : a.Name.LocalName, a => XNamespace.Get(a.Value))
     .ToList()
     .ForEach(ns => NamespaceManager.AddNamespace(string.IsNullOrWhiteSpace(ns.Key) ? defaultPrefix : ns.Key, ns.First().NamespaceName));
     DefaultToken = NamespaceManager.HasNamespace(defaultPrefix) ? defaultPrefix + ":" : "";
 }
コード例 #16
0
        private static IEnumerable<Link> GetLinks(XDocument doc, Func<string, Link> factory)
        {
            var links  = new List<Link>();

            var reader = doc.CreateReader();
            var xmlNameTable = reader.NameTable;
            _NamespaceManager = new XmlNamespaceManager(xmlNameTable);
            _NamespaceManager.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

            var elements = doc.XPathSelectElements("//xhtml:link[@href]|//xhtml:a[@href]",_NamespaceManager);
            foreach(var linkElement in elements) {
                links.AddRange(CreateLinks(linkElement, factory));
            }

            var formElements = doc.XPathSelectElements("//xhtml:form[@action]", _NamespaceManager);
            foreach (var linkElement in formElements) {
                links.AddRange(CreateFormLinks(linkElement, factory));
            }
            return links;
        }
コード例 #17
0
ファイル: ConfigProvider.cs プロジェクト: bzamecnik/XRouter
 public static Configuration ConfigurationFromXML(XDocument xmlConfig)
 {
     var xmlServices = xmlConfig.XPathSelectElements("/config/service");
     List<ServiceSettings> services = new List<ServiceSettings>();
     foreach (var xmlService in xmlServices)
     {
         services.Add(DeserializeServiceSettings(xmlService));
     }
     Configuration config = new Configuration() { Services = services };
     return config;
 }
コード例 #18
0
ファイル: CfgManager.cs プロジェクト: applelon/CodeFile
 /// <summary>
 /// 配置文件管理器
 /// </summary>
 /// <param name="filePath">文件路径</param>
 public CfgManager(string filePath)
 {
     if (!File.Exists(filePath))
     {
         throw new FileNotFoundException("配置文件不存在!");
     }
     try
     {
         _docCfg = XDocument.Load(filePath);
         _instances = _docCfg.XPathSelectElements("//instance").ToList();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #19
0
		private static void SetArtists(ArchivedAlbumContract data, ArchivedAlbumContract serialized, XDocument doc) {

			if (serialized.Artists != null && serialized.Artists.Any())
				data.Artists = serialized.Artists;
			else {

				// For backwards compatibility
				var artistElems = doc.XPathSelectElements("//ArchivedAlbumContract/Artists/ObjectRefContract"); //.Elements("Artists").Elements("ObjectRefContract"));

				data.Artists = artistElems.Select(e => new ArchivedArtistForAlbumContract {
					Id = int.Parse(e.Element("Id").Value), NameHint = e.Element("NameHint").Value 
				}).ToArray();

			}

		}
コード例 #20
0
        /// <summary>
        /// This method will parse html and try to serach the url in the html
        /// Not the best way to to parse html may be we should use the htmlagility pack
        /// </summary>
        /// <param name="sanitizedHtml"></param>
        /// <param name="urlToBeSearched"></param>
        /// <returns></returns>
        public virtual string ParseAndSearch(string sanitizedHtml, string urlToBeSearched)
        {
            IEnumerable <XElement> nextChildDivs = null;
            XElement      resultElement          = null;
            bool          matchFound             = false;
            int           counter    = 1;
            StringBuilder rankString = new StringBuilder();

            System.Xml.Linq.XDocument xd = System.Xml.Linq.XDocument.Parse(sanitizedHtml);

            resultElement = xd.XPathSelectElement("descendant::div[@id='ires']");
            nextChildDivs = xd.XPathSelectElements("descendant::div[@class='g']");

            if (nextChildDivs != null)
            {
                foreach (XElement childNode in nextChildDivs)
                {
                    var siteUrlNode = childNode.Descendants("cite").FirstOrDefault();

                    if (siteUrlNode != null && siteUrlNode.Value.Contains(urlToBeSearched))
                    {
                        if (matchFound)
                        {
                            rankString.Append(",");
                        }
                        rankString.Append(counter);
                        matchFound = true;
                    }
                    if (siteUrlNode != null)
                    {
                        counter++;
                    }
                }
            }
            if (!matchFound)
            {
                return(NoMatchFound);
            }
            else
            {
                return(rankString.ToString());
            }
        }
コード例 #21
0
		private XElement GutTarget(XDocument target)
		{
			XElement targetGroup = null;
			var elementsToRemove = new List<XElement>();
			var targetsToRemove = target.XPathSelectElements("//msbuild:ItemGroup/msbuild:Compile", _namespaceManager);
			foreach (var targetToRemove in targetsToRemove)
			{
				targetGroup = targetToRemove.Parent;

				var attrInclude = targetToRemove.Attribute(XName.Get("Include"));
				if (attrInclude == null) continue;
				if (attrInclude.Value.StartsWith(@"..\Deployer.Tests"))
					elementsToRemove.Add(targetToRemove);
			}

			elementsToRemove.ForEach(x => x.Remove());

			return targetGroup;
		}
        /// <summary>
        /// Returns any renderings that are eligible for fallback
        /// </summary>
        /// <param name="layout"></param>
        /// <param name="placeholder"></param>
        /// <returns></returns>
        private IEnumerable<XElement> GetFallbackRenderings(XDocument layout, string placeholder)
        {
            foreach (XElement renderingInPlaceholder in layout.XPathSelectElements("r/d/r[contains(@ph, '" + placeholder + "')]"))
            {
                string ph = renderingInPlaceholder.Attribute("ph").Value;

                if (ph == placeholder || ph.EndsWith("/" + placeholder))
                {
                    XAttribute renderingIdAttribute = renderingInPlaceholder.Attribute("id");

                    if (renderingIdAttribute != null)
                    {
                        if (renderingIdAttribute.Value != FALLBACK_RENDERING_ID)
                        {
                            yield return new XElement(renderingInPlaceholder);
                        }
                    }
                }
            }
        }
コード例 #23
0
        /// Metadata looks like this:
        /// <response>
        ///     <lst name="null_metadata">
        ///         <arr name="stream_source_info">
        ///             <null />
        ///         </arr>
        ///         <arr name="nbTab">
        ///             <str>10</str>
        ///         </arr>
        ///         <arr name="date">
        ///             <str>2009-06-24T15:25:00</str>
        ///         </arr>
        ///     </lst>
        /// </response>
        private List<ExtractField> ParseMetadata(XDocument response)
        {
            var metadataElements = response.XPathSelectElements("response/lst[@name='null_metadata']/arr");

            if (metadataElements == null)
            {
                return new List<ExtractField>();
            }

            var metadata = new List<ExtractField>(metadataElements.Count());
            foreach (var node in metadataElements)
            {
                var nameAttrib = node.Attribute("name");
                if (nameAttrib == null)
                {
                    throw new NotSupportedException("Metadata node has no name attribute: " + node);
                }

                // contents of the <arr> element might be a <str/> or a <null/>
                string fieldValue;
                var stringValue = node.Element("str");
                if (stringValue != null)
                {
                    // is a <str/> node
                    fieldValue = stringValue.Value;
                }
                else if (node.Element("null") != null)
                {
                    // is a <null/> node
                    fieldValue = null;
                }
                else
                {
                    throw new NotSupportedException("No support for metadata element type: " + node);
                }

                metadata.Add(new ExtractField(nameAttrib.Value, fieldValue));
            }

            return metadata;
        }
コード例 #24
0
ファイル: MainWindow.cs プロジェクト: rayros/kwejk-csharp-app
 public void LoadImages(XDocument doc)
 {
     if (posts != null) {
         foreach(VBox post in posts.Children){
             foreach (Widget obj in post.Children) {
                 post.Remove (obj);
                 obj.Destroy ();
             }
             posts.Remove (post);
             post.Destroy ();
         }
     }
     posts = new VBox ();
     vbox3.PackStart (posts,true,true,1);
     IEnumerable<XElement> posts_list = doc.XPathSelectElements("/posts/post");
     foreach (XElement elem in posts_list) {
         VBox post = new VBox ();
         string title = elem.XPathSelectElement ("title").Value;
         string description = elem.XPathSelectElement ("description").Value;
         post.PackStart (new Label (title), true, true, 1);
         IEnumerable<XElement> urls_list = elem.XPathSelectElements ("img/url");
         foreach (XElement urls in urls_list) {
             Gtk.EventBox eventBox = new Gtk.EventBox();
             string file_img_default = urls.XPathSelectElement ("default").Value;
             string file_img_original = urls.XPathSelectElement ("original").Value;
             Gtk.Image new_img = new Gtk.Image (	file_img_default);
             eventBox.Add (new_img);
             eventBox.ButtonPressEvent += delegate {
                 new Project.ImgWindow (title, description, file_img_original);
             };
             post.PackEnd (eventBox, true, true, 1);
         }
         posts.PackStart (post, true, true, 1);
     }
     posts_list = null;
     ShowAll ();
 }
コード例 #25
0
 public static IEnumerable<XElement> GetMemberNodes(XDocument doc, string memberNamePartial)
 {
     return doc.XPathSelectElements("/doc/members/member[starts-with(@name,'" + memberNamePartial + "')]");
 }
コード例 #26
0
        public static void PreprocessCodeBlocksToPreTags(GeneratorOptions options, XDocument doc)
        {
            var nodesToRemove = new List<XElement>();
            var codeNodes = doc.XPathSelectElements("//code");
            foreach (var codeNode in codeNodes)
            {
                string processedCodeSample = null;
                var xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "source");
                if (xattribute != null)
                {
                    var sourceRelativePath = xattribute.Value;

                    xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "region");
                    if (xattribute == null)
                        continue;
                    var regionName = xattribute.Value;

                    var samplePath = FindSampleCodePath(options.CodeSamplesRootFolder, sourceRelativePath);
                    if (samplePath == null)
                    {
                        Console.Error.WriteLine("Error finding sample path for {0}", sourceRelativePath);
                        continue;
                    }

                    var content = File.ReadAllText(samplePath);

                    var startPos = content.IndexOf("#region " + regionName);
                    if (startPos == -1)
                    {
                        Console.Error.WriteLine("Error finding region for {0}", regionName);
                        continue;
                    }
                    startPos = content.IndexOf('\n', startPos);
                    var endPos = content.IndexOf("#endregion", startPos);

                    processedCodeSample = content.Substring(startPos, endPos - startPos);
                }
                else
                {
                    processedCodeSample = codeNode.Value;
                }

                if (processedCodeSample != null && processedCodeSample.IndexOf('\n') > -1)
                {

                    processedCodeSample = LeftJustifyCodeBlocks(processedCodeSample);
                    var preElement = new XElement("pre", processedCodeSample);
                    preElement.SetAttributeValue("class", "brush: csharp");

                    codeNode.AddAfterSelf(preElement);
                    nodesToRemove.Add(codeNode);

                    string title = null;
                    xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "title");
                    if (xattribute != null)
                        title = xattribute.Value;

                    if (title != null)
                    {
                        var titleElement = new XElement("h4", title);
                        titleElement.SetAttributeValue("class", "csharp-code-sample-title");
                        preElement.AddBeforeSelf(titleElement);
                    }
                }
            }

            nodesToRemove.ForEach(x => x.Remove());
        }
コード例 #27
0
ファイル: ModDefinition.cs プロジェクト: nosajton/SharpTune
        private Dictionary<string, string> ReadRRLogDefExtIdentifiers(XDocument xd)
        {
            Dictionary<string, string> ls = new Dictionary<string, string>();
            string bxp = "./logger/protocols/protocol/ecuparams/ecuparam";
            IEnumerable<XElement> xbase = xd.XPathSelectElements(bxp);

            foreach (XElement xb in xbase)
            {
                ls.Add(xb.Attribute("id").Value.ToString(), xb.Attribute("name").Value.ToString());
            }

            return ls;
        }
コード例 #28
0
ファイル: ModDefinition.cs プロジェクト: nosajton/SharpTune
 private static void InheritRRLogger(ref XDocument xmlDoc, string outPath, string inheritIdent, string newIdent)
 {
     try
     {
         //inherit from a base file
         //todo add list of exemptions to skip???
         string path = "/logger/protocols/protocol[@id='SSM']/ecuparams/ecuparam/ecu[contains(@id, '" + inheritIdent + "')]";
         IEnumerable<XElement> pexp = xmlDoc.XPathSelectElements(path);
         foreach (XElement xel in pexp)
         {
             xel.Attribute("id").Value += ',' + newIdent;
         }
         xmlDoc.SaveToFile(outPath);
     }
     catch (Exception e)
     {
         Trace.WriteLine(e.Message);
     }
 }
コード例 #29
0
        public string wmGetMergedParameterXML(string sType, string sID, string sEcosystemID)
        {
            dataAccess dc = new dataAccess();
            acUI.acUI ui = new acUI.acUI();
            taskMethods tm = new taskMethods();
            FunctionTemplates.HTMLTemplates ft = new FunctionTemplates.HTMLTemplates();

            if (string.IsNullOrEmpty(sID))
                throw new Exception("ID required to look up default Parameter values.");

            string sErr = "";

            //what is the task associated with this action?
            //and get the XML for it
            string sSQL = "";
            string sDefaultsXML = "";
            string sTaskID = "";

            if (sType == "action")
            {
                sDefaultsXML = tm.wmGetObjectParameterXML(sType, sID, "");

                sSQL = "select t.task_id" +
                     " from ecotemplate_action ea" +
                     " join task t on ea.original_task_id = t.original_task_id" +
                     " and t.default_version = 1" +
                     " where ea.action_id = '" + sID + "'";
            }
            else if (sType == "instance")
            {
                sDefaultsXML = tm.wmGetObjectParameterXML(sType, sID, sEcosystemID);

                //IMPORTANT!!! if the ID is not a guid, it's a specific instance ID, and we'll need to get the task_id
                //but if it is a GUID, but the type is "instance", taht means the most recent INSTANCE for this TASK_ID
                if (ui.IsGUID(sID))
                    sTaskID = sID;
                else
                    sSQL = "select task_id" +
                         " from task_instance" +
                         " where task_instance = '" + sID + "'";
            }
            else if (sType == "plan")
            {
                sDefaultsXML = tm.wmGetObjectParameterXML(sType, sID, "");

                sSQL = "select task_id" +
                    " from action_plan" +
                    " where plan_id = '" + sID + "'";
            }
            else if (sType == "schedule")
            {
                sDefaultsXML = tm.wmGetObjectParameterXML(sType, sID, "");

                sSQL = "select task_id" +
                    " from action_schedule" +
                    " where schedule_id = '" + sID + "'";
            }

            //if we didn't get a task id directly, use the SQL to look it up
            if (string.IsNullOrEmpty(sTaskID))
                if (!dc.sqlGetSingleString(ref sTaskID, sSQL, ref sErr))
                    throw new Exception(sErr);

            if (!ui.IsGUID(sTaskID))
                throw new Exception("Unable to find Task ID for record.");

            XDocument xTPDoc = new XDocument();
            XDocument xDefDoc = new XDocument();

            //get the parameter XML from the TASK
            string sTaskParamXML = tm.wmGetParameterXML("task", sTaskID, "");
            if (!string.IsNullOrEmpty(sTaskParamXML))
            {
                xTPDoc = XDocument.Parse(sTaskParamXML);
                if (xTPDoc == null)
                    throw new Exception("Task Parameter XML data is invalid.");

                XElement xTPParams = xTPDoc.XPathSelectElement("/parameters");
                if (xTPParams == null)
                    throw new Exception("Task Parameter XML data does not contain 'parameters' root node.");
            }

            //we populated this up above too
            if (!string.IsNullOrEmpty(sDefaultsXML))
            {
                xDefDoc = XDocument.Parse(sDefaultsXML);
                if (xDefDoc == null)
                    throw new Exception("Defaults XML data is invalid.");

                XElement xDefParams = xDefDoc.XPathSelectElement("/parameters");
                if (xDefParams == null)
                    throw new Exception("Defaults XML data does not contain 'parameters' root node.");
            }

            //spin the nodes in the DEFAULTS xml, then dig in to the task XML and UPDATE the value if found.
            //(if the node no longer exists, delete the node from the defaults xml IF IT WAS AN ACTION)
            //and default "values" take precedence over task values.
            foreach (XElement xDefault in xDefDoc.XPathSelectElements("//parameter"))
            {
                //nothing to do if it's empty
                if (xDefault == null)
                    break;

                //look it up in the task param xml
                XElement xDefName = xDefault.XPathSelectElement("name");
                string sDefName = (xDefName == null ? "" : xDefName.Value);
                XElement xDefValues = xDefault.XPathSelectElement("values");

                //nothing to do if there is no values node...
                if (xDefValues == null)
                    break;
                //or if it contains no values.
                if (!xDefValues.HasElements)
                    break;
                //or if there is no parameter name
                if (string.IsNullOrEmpty(sDefName))
                    break;

                //so, we have some valid data in the defaults xml... let's merge!

                //we have the name of the parameter... go find it in the TASK param XML
                XElement xTaskParam = xTPDoc.XPathSelectElement("//parameter/name[. = '" + sDefName + "']/..");  //NOTE! the /.. gets the parent of the name node!

                //if it doesn't exist in the task params, remove it from this document, permanently
                //but only for action types... instance data is historical and can't be munged
                if (xTaskParam == null && sType == "action")
                {
                    ft.RemoveNodeFromXMLColumn("ecotemplate_action", "parameter_defaults", "action_id = '" + sID + "'", "//parameter/name[. = '" + sDefName + "']/..");
                    continue;
                }

                //is this an encrypted parameter?
                string sEncrypt = "";
                if (xTaskParam.Attribute("encrypt") != null)
                    sEncrypt = xTaskParam.Attribute("encrypt").Value;

                //and the "values" collection will be the 'next' node
                XElement xTaskParamValues = xTaskParam.XPathSelectElement("values");

                string sPresentAs = xTaskParamValues.Attribute("present_as").Value;
                if (sPresentAs == "dropdown")
                {
                    //dropdowns get a "selected" indicator
                    string sValueToSelect = xDefValues.XPathSelectElement("value").Value;

                    //find the right one by value and give it the "selected" attribute.
                    XElement xVal = xTaskParamValues.XPathSelectElement("value[. = '" + sValueToSelect + "']");
                    if (xVal != null)
                        xVal.SetAttributeValue("selected", "true");
                }
                else if (sPresentAs == "list")
                {
                    //first, a list gets ALL the values replaced...
                    xTaskParamValues.ReplaceNodes(xDefValues);
               	}
                else
                {
                    //IMPORTANT NOTE:
                    //remember... both these XML documents came from wmGetObjectParameterXML...
                    //so any encrypted data IS ALREADY OBFUSCATED and base64'd in the oev attribute.

                    //it's a single value, so just replace it with the default.
                    XElement xVal = xTaskParamValues.XPathSelectElement("value[1]");
                    if (xVal != null)
                    {
                        //if this is an encrypted parameter, we'll be replacing (if a default exists) the oev attribute
                        //AND the value... don't want them to get out of sync!
                        if (dc.IsTrue(sEncrypt))
                        {
                            if (xDefValues.XPathSelectElement("value") != null)
                                if (xDefValues.XPathSelectElement("value").Attribute("oev") != null)
                                {
                                    xVal.SetAttributeValue("oev", xDefValues.XPathSelectElement("value").Attribute("oev").Value);
                                    xVal.Value = xDefValues.XPathSelectElement("value").Value;
                                }
                        }
                        else
                        {
                            //not encrypted, just replace the value.
                            if (xDefValues.XPathSelectElement("value") != null)
                                xVal.Value = xDefValues.XPathSelectElement("value").Value;
                        }
                    }
                }
            }

            return xTPDoc.ToString(SaveOptions.DisableFormatting); ;
        }
コード例 #30
0
 protected IList<object> ExecuteXPathQuery(XDocument xDocument)
 {
     if (xDocument != null)
     {
         var elements = xDocument.XPathSelectElements(Query);
         IList<object> list = new List<object>();
         foreach (var element in elements)
         {
             list.Add(element);
         }
         return list;
     }
     Logger.AddError("Error", "In ExecuteXPathQuery method the XDocument was null.");
     return null;
 }
コード例 #31
0
        private void WriteChapter(string testamentName, string bookName, string bookCode, string chapterName, string chapterIndex, XDocument chapter)
        {
            Guard.NotNullOrEmpty(() => testamentName, testamentName);
            Guard.NotNullOrEmpty(() => bookName, bookName);
            Guard.NotNullOrEmpty(() => bookCode, bookCode);
            Guard.NotNullOrEmpty(() => chapterName, chapterName);
            Guard.NotNullOrEmpty(() => chapterIndex, chapterIndex);

            var fileDir = this.outputDir;
            var fileName = Path.Combine(fileDir, bookCode + (chapterIndex ?? "") + ".md");
            if (!Directory.Exists(fileDir))
                Directory.CreateDirectory(fileDir);

            tracer.TraceInformation("Writing {0} - {1} - {2}...", testamentName, bookName, chapterName);

            using (var file = File.CreateText(fileName))
            {
                file.WriteLine("# " + testamentName);
                file.WriteLine("## " + bookName);
                file.WriteLine("### " + chapterName);
                file.WriteLine();

                foreach (var para in chapter.XPathSelectElements("html/body/p[@class != 'Capitulo']").Where(p =>
                    p.Value.Trim().Length > 0 && p.Attribute("class") != null))
                {
                    if (para.Attribute("class").Value == "Titulointerior")
                    {
                        file.WriteLine();
                        file.WriteLine("#### " + para.Value);
                    }
                    else if (para.Attribute("class").Value == "MsoNormal")
                    {
                        var verseMatch = verseIndex.Match(para.Value);
                        if (verseMatch.Success)
                            file.WriteLine(verseMatch.Result("${index}. ${rest}"));
                        else
                            file.WriteLine(para.Value);
                    }
                }
            }
        }
コード例 #32
0
ファイル: Project.cs プロジェクト: bhuvanchandra/emul8
        protected virtual bool TryLoad(XDocument doc)
        {
            var guidNode = doc.XPathSelectElement(@"/x:Project/x:PropertyGroup/x:ProjectGuid", NamespaceManager);
            var targetNode = doc.XPathSelectElements(@"/x:Project/x:PropertyGroup/x:PlatformTarget", NamespaceManager).FirstOrDefault();
            var startupObjectNode = doc.XPathSelectElement(@"/x:Project/x:PropertyGroup/x:StartupObject", NamespaceManager);
            var referenceNodes = doc.XPathSelectElements(@"/x:Project/x:ItemGroup/x:ProjectReference", NamespaceManager).ToList();
            var forcedOutputNode = doc.XPathSelectElement(@"/x:Project/x:Target[@Name='GetForcedOutput']", NamespaceManager);

            GUID = Guid.Parse(guidNode.Value);
            StartupObject = startupObjectNode != null ? startupObjectNode.Value : string.Empty;
            Target = targetNode != null ? targetNode.Value : "Any CPU";
            var dir = System.IO.Path.GetDirectoryName(Path);

            var references = new List<Project>();
            foreach(var node in referenceNodes)
            {
                var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(dir, node.Attribute("Include").Value.Replace(@"\", "/")));
                Project project;
                if(!Project.TryLoadFromFile(path, out project))
                {
                    return false;
                }
                references.Add(project);
            }

            References = references;
            HasForcedOutput = (forcedOutputNode != null);
            return true;
        }
コード例 #33
0
ファイル: XmlHelper.cs プロジェクト: suifengshiqu/Utility
 /// <summary>
 /// 获取xpath匹配所有元素
 /// </summary>
 /// <param name="xPath">xPath表达式</param>
 /// <returns>存放匹配到的XElement的集合</returns>
 public List <XElement> GetXElements(string xPath)
 {
     return(_doc.XPathSelectElements(xPath).ToList());
 }