private static bool Rule19(string name, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { XmlElement notionalCcy = XPath.Path(context, "notional", "currency"); XmlElement paymentCcy = XPath.Path(context, "equityPremium", "paymentAmount", "currency"); if ((notionalCcy == null) || (paymentCcy == null) || !IsSameCurrency(notionalCcy, paymentCcy)) { continue; } XmlElement totalValue = XPath.Path(context, "notional", "amount"); XmlElement percentage = XPath.Path(context, "equityPremium", "percentageOfNotional"); XmlElement amount = XPath.Path(context, "equityPremium", "paymentAmount", "amount"); if ((totalValue == null) || (percentage == null) || (amount == null) || Equal(Round(ToDecimal(amount), 2), Round(ToDecimal(totalValue) * ToDecimal(percentage), 2))) { continue; } errorHandler("305", context, "The equity premium amount does not agree with the figures given for " + "the notional and premium percentage", name, null); result = false; } return(result); }
private static bool Rule21(string name, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { if (!context.ParentNode.LocalName.Equals("trade")) { continue; } if (Exists( XPath.Path(context, "calculationAgentPartyReference"))) { continue; } errorHandler("305", context, "Calculation agent field must contain a calculation agent party reference", name, null); result = false; } return(result); }
/// <summary> /// コンパイル済みのコードのバイト列を取得します. /// </summary> /// <param name="rootPath">コンパイル済みコードのルートディレクトリ</param> /// <param name="path"> コンパイル済みコードのパス </param> /// <returns> コンパイル済みのコードのバイト列 </returns> public override object GetCompiledByteCode(string rootPath, string path) { var relativePath = XPath.GetRelativePath(path, rootPath); relativePath = relativePath.Substring(0, relativePath.Length - 6).Replace('\\', '.'). Replace('/', '.'); var args = new[] { "-c", "-private", relativePath }; var info = new ProcessStartInfo { FileName = DisassembleCommand, Arguments = string.Join(" ", args), WorkingDirectory = rootPath, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, }; try { using (var p = Process.Start(info)) { var str = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if (p.ExitCode != 0) { throw new InvalidOperationException( "Failed to disassemble the exe file."); } return(str); } } catch (Win32Exception e) { throw new InvalidOperationException( "Failed to launch 'ildasmPath': " + DisassembleCommand, e); } }
private static bool Rule18(string name, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { XmlElement multiple = XPath.Path(context, "equityExercise", "equityBermudaExercise", "equityMultipleExercise"); XmlElement number = XPath.Path(context, "numberOfOptions"); if ((multiple == null) || (number == null)) { continue; } XmlElement integral = XPath.Path(multiple, "integralMultipleExercise"); XmlElement maximum = XPath.Path(multiple, "maximumNumberOfOptions"); if ((integral == null) || (maximum == null) || LessOrEqual(ToDecimal(integral) * ToDecimal(maximum), ToDecimal(number))) { continue; } errorHandler("305", context, "maximumNumberOfOptions * integralMultipleExercise should " + "not be greater than numberOfOptions", name, null); result = false; } return(result); }
private static bool Rule03 (string name, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { XmlElement end = XPath.Path (context, "endDate"); XmlElement start = XPath.Path (context, "startDate"); XmlElement fixingDate = XPath.Path (context, "rateFixingDate"); if ((start!= null) && (fixingDate != null) && Less (ToDate (start), ToDate (fixingDate))) { errorHandler ("305", context, "The rateFixingDate must not be after the startDate", name, null); result = false; } if ((end != null) && (start !=null) && Less (ToDate (end), ToDate (start))) { errorHandler ("305", context, "The startDate must not be after the endDate", name, null); result = false; } if ((end != null) && (fixingDate !=null) && Less (ToDate (end), ToDate (fixingDate))) { errorHandler ("305", context, "The rateFixingDate must not be after the endDate", name, null); result = false; } } return (result); }
private static bool Rule05 (string name, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { XmlElement costRate = XPath.Path (context, "mandatoryCostRate"); XmlElement interestRate = XPath.Path (context, "interestRate"); XmlElement margin = XPath.Path (context, "margin"); XmlElement allInRate = XPath.Path (context, "allInRate"); if ((costRate!= null) && (interestRate != null) && (margin != null) && (allInRate != null)){ decimal allInRateValue = ToDecimal (allInRate); decimal marginValue = ToDecimal (margin); decimal interestRateValue = ToDecimal (interestRate); decimal costRateValue = ToDecimal (costRate); decimal marginPlusInterest = marginValue + interestRateValue; decimal totalMarginPlusCost = marginPlusInterest + costRateValue; if (allInRateValue.CompareTo (totalMarginPlusCost) != 0) { errorHandler ("305", context, "The allInRate must be equal to margin + interestRate + mandatoryCostRate", name, null); result = false; } } } return (result); }
private static bool Rule05(string name, NodeIndex nodeIndex, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { XmlElement startDate = XPath.Path(context, "novation", "firstPeriodStartDate"); XmlAttribute href; if ((startDate == null) || (href = startDate.GetAttributeNode("href")) == null) { continue; } XmlElement target = nodeIndex.GetElementById(href.Value); if ((target == null) || !target.LocalName.Equals("party")) { errorHandler("305", context, "The @href attribute on the firstPeriodStartDate must reference a party", name, href.Value); result = false; } } return(result); }
public void ConnectAndDropConfigService_Test() { File.Copy("ConfigService.Web.config", "ConfigService.Web.config.test", true); XPath editor = new XPath(); editor.XmlFilePath = "ConfigService.Web.config.test"; string actual = editor.SelectSingleAttribute("configuration/connectionStrings/add[@name=\"configStore\"]/@connectionString"); string expected = @"Data Source=.\SQLEXPRESS;Initial Catalog=DirectConfig;Integrated Security=SSPI;"; Assert.Equal(expected, actual); editor.SetSingleAttribute("configuration/connectionStrings/add[@name=\"configStore\"]/@connectionString", @"Data Source=.\SQLEXPRESS;Initial Catalog=DirectConfig;User ID=nhindUser;Password=nhindUser!10"); actual = editor.SelectSingleAttribute("configuration/connectionStrings/add[@name=\"configStore\"]/@connectionString"); expected = @"Data Source=.\SQLEXPRESS;Initial Catalog=DirectConfig;User ID=nhindUser;Password=nhindUser!10"; Assert.Equal(expected, actual); actual = editor.SelectSingleAttribute("configuration/connectionStrings/add[@name=\"configStore\"]/@Unknown"); expected = null; Assert.Equal(expected, actual); }
private IParseTree GetFunctionBodyTree(PythonParser parser) { var parserTree = parser.funcdef(); var elementTree = XPath.FindAll(parserTree, "/*/suite", parser); return(elementTree.FirstOrDefault()); }
private static bool Rule25(string name, XmlNodeList list, ValidationErrorHandler errorHandler) { bool result = true; foreach (XmlElement context in list) { XmlElement priceCcy = XPath.Path(context, "equityPremium", "pricePerOption", "currency"); XmlElement paymentCcy = XPath.Path(context, "equityPremium", "paymentAmount", "currency"); if (!IsSameCurrency(priceCcy, paymentCcy)) { continue; } XmlElement number = XPath.Path(context, "numberOfOptions"); XmlElement priceEach = XPath.Path(context, "equityPremium", "pricePerOption", "amount"); XmlElement amount = XPath.Path(context, "equityPremium", "paymentAmount", "amount"); if ((number == null) || (priceEach == null) || (amount == null) || Equal(Round(ToDecimal(amount), 2), Round(ToDecimal(priceEach) * ToDecimal(number), 2))) { continue; } errorHandler("305", context, "The equity premium amount does not agree with the figures given for " + "the number of options and price per option", name, null); result = false; } return(result); }
/// <summary> /// Extracts the release's scheme defaults data from the XML section /// describing the schema. /// </summary> /// <param name="context">The context <see cref="XmlElement"/> for the section.</param> /// <returns>A populated <see cref="SchemeDefaults"/> instance.</returns> private SchemeDefaults GetSchemeDefaults(XmlElement context) { XmlNodeList list = XPath.Paths(context, "schemeDefault"); string [,] values = new string [list.Count, 2]; for (int index = 0; index < list.Count; ++index) { XmlElement node = list [index] as XmlElement; values [index, 0] = Types.ToToken(XPath.Path(node, "attribute")); values [index, 1] = Types.ToToken(XPath.Path(node, "schemeUri")); } list = XPath.Paths(context, "defaultAttribute"); string [,] names = new string [list.Count, 2]; for (int index = 0; index < list.Count; ++index) { XmlElement node = list [index] as XmlElement; names [index, 0] = Types.ToToken(XPath.Path(node, "attribute")); names [index, 1] = Types.ToToken(XPath.Path(node, "default")); } return(new SchemeDefaults(values, names)); }
private void AddNewItem(bool isAlert = true) { var path = SelectXPath; if (!string.IsNullOrEmpty(RootXPath)) { //TODO: 当XPath路径错误时,需要捕获异常 HtmlNode root = null; try { root = HtmlDoc.DocumentNode.SelectSingleNode(RootXPath); } catch (Exception ex) { XLogSys.Print.Error($"{RootXPath} 不能被识别为正确的XPath表达式,请检查"); } if (!(root != null).SafeCheck("使用当前父节点XPath,在文档中找不到任何父节点")) { return; } root = HtmlDoc.DocumentNode.SelectSingleNode(RootXPath)?.ParentNode; HtmlNode node = null; if ( !ControlExtended.SafeInvoke(() => HtmlDoc.DocumentNode.SelectSingleNode(path), ref node, LogType.Info, "检查子节点XPath正确性", true)) { return; } if (!(node != null).SafeCheck("使用当前子节点XPath,在文档中找不到任何子节点")) { return; } if (!node.IsAncestor(root) && isAlert) { if ( MessageBox.Show("当前XPath所在节点不是父节点的后代,请检查对应的XPath,是否依然要添加?", "提示信息", MessageBoxButton.YesNo) == MessageBoxResult.No) { return; } } path = XPath.TakeOff(node.XPath, root.XPath); } if (CrawlItems.FirstOrDefault(d => d.Name == SelectName) == null || MessageBox.Show("已经存在同名的属性,是否依然添加?", "提示信息", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { var item = new CrawlItem { XPath = path, Name = SelectName, SampleData1 = SelectText }; CrawlItems.Add(item); SelectXPath = ""; SelectName = ""; XLogSys.Print.Info("成功添加属性"); } }
protected override QuoteOptionsResult ConvertResult(YahooManaged.Base.ConnectionInfo connInfo, System.IO.Stream stream, YahooManaged.Base.SettingsBase settings) { List <QuoteOptionsDataChain> options = new List <QuoteOptionsDataChain>(); System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US"); XDocument doc = MyHelper.ParseXmlDocument(stream); XElement[] mainLst = XPath.GetElements("//optionsChain", doc); foreach (XElement chain in mainLst) { string idAtt = MyHelper.GetXmlAttributeValue(chain, "symbol"); string expirationDateAtt = MyHelper.GetXmlAttributeValue(chain, "expiration"); DateTime expirationDate = default(DateTime); if (!System.DateTime.TryParseExact(expirationDateAtt, "yyyy-MM-dd", culture, System.Globalization.DateTimeStyles.None, out expirationDate)) { System.DateTime.TryParseExact(expirationDateAtt, "yyyy-MM", culture, System.Globalization.DateTimeStyles.None, out expirationDate); } List <QuoteOptionsData> lst = new List <QuoteOptionsData>(); foreach (XElement optionNode in chain.Elements()) { if (optionNode.Name.LocalName == "option") { QuoteOptionsData opt = ImportExport.ToQuoteOption(optionNode, culture); if (opt != null) { lst.Add(opt); } } } options.Add(new QuoteOptionsDataChain(idAtt, expirationDate, lst)); } return(new QuoteOptionsResult(options.ToArray())); }
private void AssertTree(VBAParser parser, ParserRuleContext root, string xpath, Predicate <ICollection <IParseTree> > assertion) { var matches = new XPath(parser, xpath).Evaluate(root); var actual = matches.Count; Assert.IsTrue(assertion(matches), string.Format("{0} matches found.", actual)); }
private static string[] XPath_GetValues(XObject node, XPath xp) { if (node == null || xp.XmlXPath == null || !(node is XNode)) { return(new string[0]); } IEnumerable <XObject> nodes = ((XNode)node).zXPathNodes(xp.XmlXPath); List <string> al = new List <string>(); foreach (XObject node2 in nodes) { if (!XPath_FindAttrib(xp.FindAttrib, node2)) { continue; } if (node2.zGetValue() != null) { al.Add(node2.zGetValue()); } } string[] sValues = new string[al.Count]; for (int i = 0; i < al.Count; i++) { sValues[i] = (string)al[i]; } return(sValues); }
protected override NasdaqEarningForecastResult ConvertResult(Base.ConnectionInfo connInfo, System.IO.Stream stream, Base.SettingsBase settings) { List <NasdaqEarningForecastData> yearly = new List <NasdaqEarningForecastData>(10); List <NasdaqEarningForecastData> quarterly = new List <NasdaqEarningForecastData>(10); System.Globalization.CultureInfo culture = Factory.DownloadCultureInfo; string pattern = @"<title>.*\((\w*)\).*</title>"; if (stream != null) { var content = MyHelper.StreamToString(stream, System.Text.Encoding.UTF8); var matchPattern = "(<div class=\"genTable\">.*?</div>)"; var match = Regex.Matches(content, matchPattern, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant); XParseDocument year = MyHelper.ParseXmlDocument(match[0].Groups[0].Value); XParseDocument quarter = MyHelper.ParseXmlDocument(match[1].Groups[0].Value); var symbol = Regex.Match(content, pattern).Groups[1].Value; var resultNode = XPath.GetElement("//table", year); ParseTable(yearly, resultNode, symbol, ""); resultNode = XPath.GetElement("//table", quarter); ParseTable(quarterly, resultNode, symbol, ""); return(new NasdaqEarningForecastResult(yearly.ToArray(), quarterly.ToArray())); } return(null); }
public void ReplaceFragment_Empty_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); string emptyFragment = @""; string xpath = "/SmtpAgentConfig/Domain"; XPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; //var original = editor.SelectSingleAttribute("xpath"); XmlDocument originalDocument = new XmlDocument(); originalDocument.Load("SmtpAgentConfig.xml.test"); XmlNode domainNode = originalDocument.SelectSingleNode(xpath); Assert.NotNull(domainNode); //Act editor.ReplaceFragment(xpath, emptyFragment); //Assert XmlDocument updatedDocument = new XmlDocument(); updatedDocument.Load("SmtpAgentConfig.xml.test"); domainNode = updatedDocument.SelectSingleNode(xpath); Assert.Null(domainNode); }
public void AddingNodes_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); XPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; // // Ensure I am using it right // var actual = editor.SelectSingleAttribute("/SmtpAgentConfig/DomainManager/Url"); var expected = "http://localhost/ConfigService/DomainManagerService.svc/Domains"; Assert.Equal(expected, actual); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url"); expected = null; Assert.Equal(expected, actual); editor.CreateFragment("/SmtpAgentConfig/MdnMonitor/Url"); editor.SetSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url", @"http://localhost/ConfigService/MonitorService.svc/Dispositions"); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url"); expected = @"http://localhost/ConfigService/MonitorService.svc/Dispositions"; Assert.Equal(expected, actual); }
private void AddNewItem(bool isAlert = true) { var path = SelectXPath; if (!string.IsNullOrEmpty(RootXPath)) { var root = HtmlDoc.DocumentNode.SelectSingleNode(RootXPath).ParentNode; var node = HtmlDoc.DocumentNode.SelectSingleNode(path); if (!node.IsAncestor(root)) { if (isAlert) { MessageBox.Show("当前XPath所在节点不是父节点的后代,请检查对应的XPath"); } return; } path = new XPath(node.XPath).TakeOff(root.XPath).ToString(); } var item = new CrawlItem { XPath = path, Name = SelectName, SampleData1 = SelectText }; if (CrawlItems.Any(d => d.Name == SelectName)) { SelectName = "属性" + CrawlItems.Count; if (isAlert) { MessageBox.Show($"已存在名称为{SelectName}的属性,不能重复添加"); return; } } CrawlItems.Add(item); SelectXPath = ""; }
private void OrderSwapStreams(XmlElement context, XmlDocument document, XmlElement parent) { List <XmlNode> fixedStreams = new List <XmlNode> (); List <XmlNode> floatStreams = new List <XmlNode> (); // TODO inflation foreach (XmlNode node in XPath.Paths(context, "swapStream")) { if (XPath.Path((XmlElement)node, "calculationPeriodAmount", "calculation", "fixedRateSchedule") != null) { fixedStreams.Add(node); } else if (XPath.Path((XmlElement)node, "calculationPeriodAmount", "calculation", "floatingRateCalculation") != null) { floatStreams.Add(node); } } fixedStreams.Sort(CompareSwapStreamFixedRates); floatStreams.Sort(CompareSwapStreamFloatingRates); foreach (XmlNode node in fixedStreams) { Transcribe(node, document, parent); } foreach (XmlNode node in floatStreams) { Transcribe(node, document, parent); } }
private IParseTree GetFunctionTree(PythonParser parser) { var parserTree = parser.root(); var elementTree = XPath.FindAll(parserTree, "//funcdef", parser); return(elementTree.FirstOrDefault()); }
/// <summary> /// Retrieve all the XPaths for the given key and the given index, and then extract them from the XmlDocument, using regexp whenever existing. /// /// The index is ignored if < 0. /// </summary> /// <param name="stuffName"></param> /// <param name="doc"></param> /// <param name="index"></param> /// <returns></returns> public static StringDictionary getData(string stuffName, XmlDocument doc, int index) { StringDictionary data = new StringDictionary(); List <string> Keys = XPath.getKeys(stuffName); foreach (string Key in Keys) { String value = (index >= 0 ? getValueFromXPath(doc, Key, index) : getValueFromXPath(doc, Key)); Regex regExp = RegExp.get(Key); if (!(regExp == null)) { String valueMatch = RegExp.matchRegexInfo(regExp, value); if (valueMatch == null) { LogUtils.warn("RegEx match failed for regexp " + regExp.ToString() + " on value " + value); value = ""; } else { value = valueMatch; } } value = formatValue(value, Key); data.Add(KeyUtils.getKeyWithoutName(Key, stuffName), value); // We remove the key name from the data } return(data); }
public void RemovingBackupIpNode_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); var editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; var actual = editor.SelectSingleAttribute("/SmtpAgentConfig/PublicCerts/DnsResolver/BackupIpAddress"); Assert.Null(actual); editor.CreateFragment("/SmtpAgentConfig/PublicCerts/DnsResolver/BackupIpAddress"); var expected = "8.8.8.8"; editor.SetSingleAttribute("/SmtpAgentConfig/PublicCerts/DnsResolver/BackupIpAddress", expected); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/PublicCerts/DnsResolver/BackupIpAddress"); Assert.Equal(expected, actual); // now delete editor.DeleteNode("/SmtpAgentConfig/PublicCerts/DnsResolver/BackupIpAddress"); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/PublicCerts/DnsResolver/BackupIpAddress"); Assert.Null(actual); }
public IDictionary <string, int> Search(Stream[] xmlStreams, string xPathString) { var xPath = XPath.ParseFrom(xPathString); var data = new Dictionary <string, int>(); Parallel.For( 0, xmlStreams.Length, new ParallelOptions { MaxDegreeOfParallelism = _maxThreadsCount }, i => { var result = SearchOne(xmlStreams[i], xPath); lock (data) { if (data.ContainsKey(result)) { data[result]++; } else { data.Add(result, 1); } } }); return(data); }
private static void ParseTable(List <NasdaqEarningForecastData> yearly, XParseElement sourceNode, string symbol, string xPath) { var resultNode = sourceNode; if (!(string.IsNullOrWhiteSpace(xPath) || string.IsNullOrEmpty(xPath))) { resultNode = XPath.GetElement(xPath, sourceNode); } int cnt = 0; float tempVal; if (resultNode != null) { foreach (XParseElement node in resultNode.Elements()) { if (node.Name.LocalName == "tr") { cnt++; if (cnt > 1) // skip row header { XParseElement tempNode = null; var data = new NasdaqEarningForecastData(); data.SetID(symbol); tempNode = XPath.GetElement("/td[1]", node); if (tempNode != null) { data.FiscalEnd = HttpUtility.HtmlDecode(tempNode.Value); } tempNode = XPath.GetElement("/td[2]", node); float.TryParse(tempNode.Value, out tempVal); data.ConsensusEpsForecast = tempVal; tempNode = XPath.GetElement("/td[3]", node); float.TryParse(tempNode.Value, out tempVal); data.HighEpsForecast = tempVal; tempNode = XPath.GetElement("/td[4]", node); float.TryParse(tempNode.Value, out tempVal); data.LowEpsForecast = tempVal; tempNode = XPath.GetElement("/td[5]", node); float.TryParse(tempNode.Value, out tempVal); data.NumberOfEstimate = (int)tempVal; tempNode = XPath.GetElement("/td[6]", node); float.TryParse(tempNode.Value, out tempVal); data.NumOfRevisionUp = (int)tempVal; tempNode = XPath.GetElement("/td[7]", node); float.TryParse(tempNode.Value, out tempVal); data.NumOfrevisionDown = (int)tempVal; yearly.Add(data); } } } } }
[Test] public void XpathExistsTrueForXpathThatExists() { XPath xpath = new XPath(EXISTENT_XPATH); Assert.AreEqual(true, xpath.XPathExists(SIMPLE_XML)); }
/// <summary> /// Asserts that the flattened String obtained by executing an Xpath on some XML is a particular value /// </summary> /// <param name="anXPathExpression">An X path expression.</param> /// <param name="inXml">The XML to test.</param> /// <param name="expectedValue">The expected value.</param> public static void XPathEvaluatesTo(string anXPathExpression, XmlInput inXml, string expectedValue) { XPath xpath = new XPath(anXPathExpression); OldAssert.AreEqual(expectedValue, xpath.EvaluateXPath(inXml)); }
[Test] public void XpathExistsFalseForUnmatchedExpression() { XPath xpath = new XPath(NONEXISTENT_XPATH); Assert.AreEqual(false, xpath.XPathExists(SIMPLE_XML)); }
public void XpathEvaluatesCountExpression() { string expectedValue = "2"; XPath xpath = new XPath(COUNT_XPATH); Assert.AreEqual(expectedValue, xpath.EvaluateXPath(MORE_COMPLEX_XML)); }
public virtual string GetText() { Sync(); dynamic dval = Chrome.Driver.Eval("document.evaluate('" + XPath.Replace("'", "\\\\'") + "', document.documentElement, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ).snapshotItem(0).innerText"); return(dval.result.result.value); }
public void XpathEvaluatesMultiNodeExpression() { string expectedValue = "onetwo"; XPath xpath = new XPath(MULTI_NODE_XPATH); Assert.AreEqual(expectedValue, xpath.EvaluateXPath(MORE_COMPLEX_XML)); }
public void XpathEvaluatesToEmptyStringForUnmatchedExpression() { string expectedValue = ""; XPath xpath = new XPath(NONEXISTENT_XPATH); Assert.AreEqual(expectedValue, xpath.EvaluateXPath(SIMPLE_XML)); }
public FrameFinder(IWebDriver selenium, ElementFinder elementFinder, XPath xPath, SeleniumWindowManager seleniumWindowManager) { this.selenium = selenium; this.elementFinder = elementFinder; this.xPath = xPath; this.seleniumWindowManager = seleniumWindowManager; }
public void XpathEvaluatesToTextValueForSimpleString() { string expectedValue = "one two"; XPath xpath = new XPath(EXISTENT_XPATH); Assert.AreEqual(expectedValue, xpath.EvaluateXPath(SIMPLE_XML)); }
public void QueryTest() { XPath editor = new XPath(); editor.XmlFilePath = "DirectDnsResponderSvc.exe.config"; string value = editor.SelectSingleAttribute(@"/configuration/ServiceSettingsGroup/RecordRetrievalServiceSettings/@Url"); string expected = @"http://localhost/DnsService/RecordRetrievalService.svc/Records"; Assert.Equal(expected, value); }
protected SeleniumWebDriver(IWebDriver webDriver, Browser browser) { this.webDriver = webDriver; this.browser = browser; xPath = new XPath(browser.UppercaseTagNames); elementFinder = new ElementFinder(); frameFinder = new FrameFinder(this.webDriver, elementFinder,xPath); textMatcher = new TextMatcher(); windowHandleFinder = new WindowHandleFinder(this.webDriver); dialogs = new Dialogs(this.webDriver); mouseControl = new MouseControl(this.webDriver); }
// Use this for initialization void Start() { Seeker seeker = GetComponent<Seeker>(); seeker.pathCallback = OnPathComplete; //Create a new XPath with a custom ending condition XPath p = new XPath (transform.position,targetPoint.position,null); p.endingCondition = new CEC (p, hLimit); //Draw a line in black from the start to the target point Debug.DrawLine (transform.position,targetPoint.position,Color.black); seeker.StartPath (p); }
protected SeleniumWebDriver(IWebDriver webDriver, Browser browser) { this.webDriver = webDriver; this.browser = browser; xPath = new XPath(); elementFinder = new ElementFinder(xPath); fieldFinder = new FieldFinder(elementFinder, xPath); frameFinder = new FrameFinder(this.webDriver, elementFinder,xPath); textMatcher = new TextMatcher(); buttonFinder = new ButtonFinder(elementFinder, textMatcher, xPath); sectionFinder = new SectionFinder(elementFinder, textMatcher); dialogs = new Dialogs(this.webDriver); mouseControl = new MouseControl(this.webDriver); optionSelector = new OptionSelector(); }
protected SeleniumWebDriver(RemoteWebDriver webDriver) { selenium = webDriver; xPath = new XPath(); scoping = new Scoping(selenium); elementFinder = new ElementFinder(scoping,xPath); fieldFinder = new FieldFinder(elementFinder, xPath); iframeFinder = new IFrameFinder(selenium, elementFinder,xPath); textMatcher = new TextMatcher(); buttonFinder = new ButtonFinder(elementFinder, textMatcher, xPath); sectionFinder = new SectionFinder(elementFinder, textMatcher); dialogs = new Dialogs(selenium); mouseControl = new MouseControl(selenium); optionSelector = new OptionSelector(); }
public void ConnectAndDropDirectDnsResponder_Test() { File.Copy("DirectDnsResponderSvc.exe.config", "DirectDnsResponderSvc.exe.config.test", true); XPath editor = new XPath(); editor.XmlFilePath = "DirectDnsResponderSvc.exe.config.test"; string value = editor.SelectSingleAttribute(@"/configuration/ServiceSettingsGroup/RecordRetrievalServiceSettings/@Url"); string expected = @"http://localhost/DnsService/RecordRetrievalService.svc/Records"; Assert.Equal(expected, value); editor.SetSingleAttribute(@"/configuration/ServiceSettingsGroup/RecordRetrievalServiceSettings/@Url", @"http://SomeServer/DnsService/RecordRetrievalService.svc/Records" ); value = editor.SelectSingleAttribute(@"/configuration/ServiceSettingsGroup/RecordRetrievalServiceSettings/@Url"); expected = @"http://SomeServer/DnsService/RecordRetrievalService.svc/Records"; Assert.Equal(expected, value); }
public void GetDomain_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); XPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; string actual = editor.SelectSingleAttribute("/SmtpAgentConfig/Domain"); string expected = "Direct.North.Hobo.Lab"; Assert.Equal(expected, actual); editor.SetSingleAttribute("/SmtpAgentConfig/Domain", "Direct.South.Hobo.Lab"); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/Domain"); expected = "Direct.South.Hobo.Lab"; Assert.Equal(expected, actual); }
public SectionFinder(ElementFinder elementFinder, XPath xPath) { this.elementFinder = elementFinder; this.xPath = xPath; }
public void CreateFragmentBefore_Create_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); string domainsFragement = @"<Domains><ServiceResolver><AgentName>SmtpAgent1</AgentName><ClientSettings><Url>http://localhost/ConfigService/DomainManagerService.svc/Domains</Url></ClientSettings><CacheSettings><Cache>true</Cache><CacheTTLSeconds>20</CacheTTLSeconds></CacheSettings></ServiceResolver></Domains>"; string xpath = "/SmtpAgentConfig/Domains"; IPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; //var original = editor.SelectSingleAttribute("xpath"); //Act editor.CreateFragmentBefore(domainsFragement, "//DomainManager"); //Assert XmlDocument updatedDocument = new XmlDocument(); updatedDocument.Load("SmtpAgentConfig.xml.test"); XmlNode updatedAnchors = updatedDocument.SelectSingleNode(xpath); XmlWriterSettings settings = new XmlWriterSettings(); settings.NewLineChars = string.Empty; settings.Indent = false; settings.IndentChars = ""; settings.ConformanceLevel = ConformanceLevel.Auto; string actualFragment; using (var stringWriter = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(stringWriter, settings)) { updatedAnchors.WriteTo(writer); writer.Flush(); actualFragment = stringWriter.ToString(); } } string expectedFragment; using (var stringWriter = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(stringWriter, settings)) { XmlNode newNode = updatedDocument.CreateDocumentFragment(); newNode.InnerXml = domainsFragement; newNode.WriteTo(writer); writer.Flush(); expectedFragment = stringWriter.ToString(); } } XmlDocument cleanExpectedFragment = new XmlDocument(); cleanExpectedFragment.LoadXml(expectedFragment); expectedFragment = cleanExpectedFragment.OuterXml; Assert.Equal(expectedFragment, actualFragment); }
private static bool IsSameXPath(string xpath1, string xpath2, string shortv) { var p1 = new XPath(xpath1).TakeOff(shortv); var p2 = new XPath(xpath2).TakeOff(shortv); return p1.ToString() == p2.ToString(); }
public void AddingNodes_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); XPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; // // Ensure I am using it right // var actual = editor.SelectSingleAttribute("/SmtpAgentConfig/DomainManager/Url"); var expected = "http://localhost/ConfigService/DomainManagerService.svc/Domains"; Assert.Equal(expected, actual); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url"); expected = null; Assert.Equal(expected, actual); editor. CreateFragment("/SmtpAgentConfig/MdnMonitor/Url"); editor.SetSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url", @"http://localhost/ConfigService/MonitorService.svc/Dispositions"); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url"); expected = @"http://localhost/ConfigService/MonitorService.svc/Dispositions"; Assert.Equal(expected, actual); }
internal ElementFinder() { xPath = new XPath(); }
public FieldFinder(ElementFinder elementFinder, XPath xPath) { this.elementFinder = elementFinder; this.xPath = xPath; }
public ElementFinder(Scoping scoping, XPath xPath) { this.scoping = scoping; this.xPath = xPath; }
public void XpathExistsFalseForUnmatchedExpression() { XPath xpath = new XPath(NONEXISTENT_XPATH); Assert.AreEqual(false, xpath.XPathExists(SIMPLE_XML)); }
public void XpathExistsTrueForXpathThatExists() { XPath xpath = new XPath(EXISTENT_XPATH); Assert.AreEqual(true, xpath.XPathExists(SIMPLE_XML)); }
/// <summary> /// 计算可能是列表根节点的概率,同时将值保存在dict中。 /// </summary> /// <param name="node"></param> /// <param name="dict"></param> private static void GetTableRootProbability(IList<HtmlNode> nodes, Dictionary<string, double> dict, bool haschild) { if (nodes.Count == 0) return; var node = nodes[0]; var xpath = new XPath(node.XPath).RemoveFinalNum().ToString(); if (haschild) { foreach (var htmlNode in nodes) { GetTableRootProbability(htmlNode.ChildNodes.Where(d => d.Name.Contains("#") == false).ToList(), dict, haschild); } } var avanode = nodes.ToList(); if (avanode.Count < 3) return; if (avanode.Count(d => d.Name == avanode[1].Name) < avanode.Count*0.7) return; var childCount = (double) avanode.Count; var childCounts = avanode.Select(d => (double) d.ChildNodes.Count).ToArray(); var v = childCounts.Variance(); //TODO: 此处需要一个更好的手段,因为有效节点往往是间隔的 if (v > 5) { return; } var leafCount = avanode.First().GetLeafNodeCount(); var value = childCount*PM25 + leafCount; dict.SetValue(xpath, value); }
private void AddNewItem(bool isAlert = true) { var path = SelectXPath; if (!string.IsNullOrEmpty(RootXPath)) { var root = HtmlDoc.DocumentNode.SelectSingleNode(RootXPath).ParentNode; var node = HtmlDoc.DocumentNode.SelectSingleNode(path); if (!node.IsAncestor(root)) { if (isAlert) MessageBox.Show("当前XPath所在节点不是父节点的后代,请检查对应的XPath"); return; } path = new XPath(node.XPath).TakeOff(root.XPath).ToString(); } var item = new CrawlItem {XPath = path, Name = SelectName, SampleData1 = SelectText}; if (CrawlItems.Any(d => d.Name == SelectName)) { SelectName = "属性" + CrawlItems.Count; if (isAlert) { MessageBox.Show($"已存在名称为{SelectName}的属性,不能重复添加"); return; } } CrawlItems.Add(item); SelectXPath = ""; }
public ButtonFinder(ElementFinder elementFinder, TextMatcher textMatcher, XPath xPath) { this.elementFinder = elementFinder; this.textMatcher = textMatcher; this.xPath = xPath; }
public FrameFinder(IWebDriver selenium, ElementFinder elementFinder, XPath xPath) { this.selenium = selenium; this.elementFinder = elementFinder; this.xPath = xPath; }
public void DeletingNodes_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); XPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; editor.CreateFragment("/SmtpAgentConfig/MdnMonitor/Url"); editor.SetSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url", @"http://localhost/ConfigService/MonitorService.svc/Dispositions"); var actual = editor.SelectSingleAttribute("/SmtpAgentConfig/MdnMonitor/Url"); var expected = @"http://localhost/ConfigService/MonitorService.svc/Dispositions"; Assert.Equal(expected, actual); editor.DeleteFragment("/SmtpAgentConfig/MdnMonitor"); actual = editor.SelectSingleAttribute("/SmtpAgentConfig/MdnMonitor"); Assert.Null(actual); }
public void ReplaceFragment_Test() { File.Copy("SmtpAgentConfig.xml", "SmtpAgentConfig.xml.test", true); string anchorsPlugin = @"<Anchors> <PluginResolver> <!-- NEW Resolver that COMBINES Anchors from multiple sources into a single list--> <Definition> <TypeName>Health.Direct.ResolverPlugins.MultiSourceAnchorResolver, Health.Direct.ResolverPlugins</TypeName> <Settings> <!-- New Bundle Resolver --> <BundleResolver> <ClientSettings> <Url>http://localhost/ConfigService/CertificateService.svc/Bundles</Url> </ClientSettings> <CacheSettings> <Cache>true</Cache> <NegativeCache>true</NegativeCache> <!-- Set cache to longer duration in production --> <CacheTTLSeconds>60</CacheTTLSeconds> </CacheSettings> <MaxRetries>1</MaxRetries> <Timeout>30000</Timeout> <!-- In milliseconds --> <VerifySSL>true</VerifySSL> </BundleResolver> <!-- Standard Resolver that pulls from Anchor store --> <ServiceResolver> <ClientSettings> <Url>http://localhost/ConfigService/CertificateService.svc/Anchors</Url> </ClientSettings> <CacheSettings> <Cache>true</Cache> <NegativeCache>true</NegativeCache> <CacheTTLSeconds>60</CacheTTLSeconds> </CacheSettings> </ServiceResolver> </Settings> </Definition> </PluginResolver> </Anchors>"; string xpath = "/SmtpAgentConfig/Anchors"; XPath editor = new XPath(); editor.XmlFilePath = "SmtpAgentConfig.xml.test"; //var original = editor.SelectSingleAttribute("xpath"); //Act editor.ReplaceFragment(xpath, anchorsPlugin); //Assert XmlDocument updatedDocument = new XmlDocument(); updatedDocument.Load("SmtpAgentConfig.xml.test"); XmlNode updatedAnchors = updatedDocument.SelectSingleNode(xpath); XmlWriterSettings settings = new XmlWriterSettings(); settings.NewLineChars = string.Empty; settings.Indent = false; settings.IndentChars = ""; settings.ConformanceLevel = ConformanceLevel.Auto; string actualFragment; using(var stringWriter = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(stringWriter, settings)) { updatedAnchors.WriteTo(writer); writer.Flush(); actualFragment = stringWriter.ToString(); } } string expectedFragment; using (var stringWriter = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(stringWriter, settings)) { XmlNode newNode = updatedDocument.CreateDocumentFragment(); newNode.InnerXml = anchorsPlugin; newNode.WriteTo(writer); writer.Flush(); expectedFragment = stringWriter.ToString(); } } XmlDocument cleanExpectedFragment = new XmlDocument(); cleanExpectedFragment.LoadXml(expectedFragment); expectedFragment = cleanExpectedFragment.OuterXml; Assert.Equal(expectedFragment, actualFragment); }
public ElementFinder(XPath xPath) { this.xPath = xPath; }