public static string GetShortUrl(string longUrl) { string url = string.Format("http://api.bit.ly/shorten?format=xml&version=2.0.1&longUrl={0}&login={1}&apiKey={2}", HttpUtility.UrlEncode(longUrl), login, apiKey); try { System.Net.WebClient we = new System.Net.WebClient(); string ret = we.DownloadString(url); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(ret); System.Xml.XmlNode xnode = doc.DocumentElement.SelectSingleNode("results/nodeKeyVal/shortUrl"); if (!System.String.IsNullOrEmpty(xnode.InnerText)) { return xnode.InnerText; } else { throw new Exception("Unable to shorten URL"); } } catch (Exception) { throw; } }
// GET: Encuesta public ActionResult Index() { //XMLReader readXML = new XMLReader(); //var data = readXML.RetrunListOfEncuesta(); //Session["Resp"] = null; Session["dictionary"] = null; var dictionary = new Dictionary<string, string>(); Session["dictionary"] = dictionary; Session["ENCUESTA_ID"] = null; System.Xml.XmlDocument xDocumento = new System.Xml.XmlDocument(); List<Encuesta> data = new List<Encuesta>(); ServiceITLProxy.ServiceITL obj = new ServiceITLProxy.ServiceITL(); var sRespuesta = obj.Encuesta(""); if (sRespuesta != null) { xDocumento.LoadXml(sRespuesta); XMLReader readXML = new XMLReader(); data = readXML.ReturnListOfEncuesta(xDocumento); } return View(data.ToList()); }
public static object deserialize(string json, Type type) { try { if (json.StartsWith("{") || json.StartsWith("[")) return JsonConvert.DeserializeObject(json, type); else { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(json); return JsonConvert.SerializeXmlNode(xmlDoc); } } catch (IOException e) { throw new ApiException(500, e.Message); } catch (JsonSerializationException jse) { throw new ApiException(500, jse.Message); } catch (System.Xml.XmlException xmle) { throw new ApiException(500, xmle.Message); } }
/// <summary> /// 新建 /// </summary> /// <returns></returns> public static System.Xml.XmlDocument NewXmlDocument() { System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?> <Root/>"); return xd; }
public void RT1() { var doc = new XmlDocument(); doc.Begin("bookstore") .Add("locations") .Add("location", new { store_id = "1", address = "21 Jump St", phone = "123456"}).Up() .Add("location", new { store_id = "2", address = "342 Pitt St", phone = "9876543"}).Up() .Up() .Add("books") .Add("book", new {title = "The Enchiridion", price = "9.75"}) .Add("author", "Epictetus").Up() .Add("stores_with_stock") .Add("store", new { store_id = "1"}).Up() .Up() .Up() .Add("book", new {title = "Signal to Noise", price = "5.82"}) .Add("author", "Neil Gaiman").Up() .Add("author", "Dave McKean").Up() .Add("stores_with_stock") .Add("store", new { store_id = "1"}).Up() .Add("store", new { store_id = "2"}).Up() .Up() .Up() .Up() .Add("staff") .Add("member", new { firstname = "Ben", lastname = "Hughes", staff_id = "123"}).Up() .Add("member", new { firstname = "Freddie", lastname = "Smith", staff_id = "124"}).Up(); Assert.AreEqual(Resource.BookstoreExpectedNotPretty, doc.ToString()); Assert.AreEqual(Resource.BookstoreExpectedPretty, doc.ToString(true)); var xmlDoc = new System.Xml.XmlDocument(); Assert.DoesNotThrow(() => xmlDoc.LoadXml(doc.ToString())); }
public void DeserializeBannerTestSuccessfull() { string content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Banners><Banner><id>605881</id><BannerPath>fanart/original/83462-18.jpg</BannerPath><BannerType>fanart</BannerType><BannerType2>1920x1080</BannerType2><Colors>|217,177,118|59,40,68|214,192,205|</Colors><Language>de</Language><Rating>9.6765</Rating><RatingCount>34</RatingCount><SeriesName>false</SeriesName><ThumbnailPath>_cache/fanart/original/83462-18.jpg</ThumbnailPath><VignettePath>fanart/vignette/83462-18.jpg</VignettePath></Banner></Banners>"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(content); System.Xml.XmlNode bannersNode = doc.ChildNodes[1]; System.Xml.XmlNode bannerNode = bannersNode.ChildNodes[0]; Banner target = new Banner(); target.Deserialize(bannerNode); Assert.Equal(605881, target.Id); Assert.Equal("fanart/original/83462-18.jpg", target.BannerPath); Assert.Equal(BannerTyp.fanart, target.Type); Assert.Equal("1920x1080", target.Dimension); Assert.Equal("|217,177,118|59,40,68|214,192,205|", target.Color); Assert.Equal("de", target.Language); Assert.Equal(9.6765, target.Rating); Assert.Equal(34, target.RatingCount); Assert.Equal(false, target.SeriesName); Assert.Equal("_cache/fanart/original/83462-18.jpg", target.ThumbnailPath); Assert.Equal("fanart/vignette/83462-18.jpg", target.VignettePath); }
public ActionResult RazonSocial(string rutempresa) { System.Xml.XmlDocument xDocumento = new System.Xml.XmlDocument(); servMEDAtencionProxy.servMEDAtencion obj = new servMEDAtencionProxy.servMEDAtencion(); var sRespuesta = obj.wsValidaEmpSiso(rutempresa); if (sRespuesta != null) { xDocumento.LoadXml(sRespuesta); XMLReader readXML = new XMLReader(); var data = readXML.ReturnListOfEmpresa(xDocumento); if (data[0].GlsError != null) { string razonsocial = data[0].GlsError; string[] razonsocial2 = razonsocial.Split(';'); if (razonsocial2.Count() > 1) { return Json(new { razonsocial = razonsocial2[1] }); } else { return Json(new { razonsocial = razonsocial2[0] }); } } } return Json(new { razonsocial = "No existe" }); }
private void btnSave_Click(object sender, System.EventArgs e) { //Save the values to an XML file //Could save to data source, Message Queue, etc. System.Xml.XmlDocument aDOM = new System.Xml.XmlDocument(); System.Xml.XmlAttribute aAttribute; aDOM.LoadXml("<PersonnelData/>"); //Add the First Name attribute to XML aAttribute = aDOM.CreateAttribute("FirstName"); aAttribute.Value = txtFName.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Add the Last Name attribute to XML aAttribute = aDOM.CreateAttribute("LastName"); aAttribute.Value = txtLName.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Add the DOB attribute to XML aAttribute = aDOM.CreateAttribute("DOB"); aAttribute.Value = txtDOB.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Add the SSN attribute to XML aAttribute = aDOM.CreateAttribute("SSN"); aAttribute.Value = txtSSN.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Save file to the file system aDOM.Save("PersonnelData.xml"); }
private void btnSave_Click(object sender, System.EventArgs e) { //Save the values to an XML file //Could save to data source, Message Queue, etc. System.Xml.XmlDocument aDOM = new System.Xml.XmlDocument(); System.Xml.XmlAttribute aAttribute; aDOM.LoadXml("<AutomobileData/>"); //Add the First Name attribute to XML aAttribute = aDOM.CreateAttribute("Manufacturer"); aAttribute.Value = txtManufact.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Add the Last Name attribute to XML aAttribute = aDOM.CreateAttribute("Model"); aAttribute.Value = txtModel.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Add the DOB attribute to XML aAttribute = aDOM.CreateAttribute("Year"); aAttribute.Value = txtYear.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Add the SSN attribute to XML aAttribute = aDOM.CreateAttribute("Color"); aAttribute.Value = txtColor.Text; aDOM.DocumentElement.Attributes.Append(aAttribute); //Save file to the file system aDOM.Save("AutomobileData.xml"); }
public static ImageInfo toImgur(Bitmap bmp) { ImageConverter convert = new ImageConverter(); byte[] toSend = (byte[])convert.ConvertTo(bmp, typeof(byte[])); using (WebClient wc = new WebClient()) { NameValueCollection nvc = new NameValueCollection { { "image", Convert.ToBase64String(toSend) } }; wc.Headers.Add("Authorization", Imgur.getAuth()); ImageInfo info = new ImageInfo(); try { byte[] response = wc.UploadValues("https://api.imgur.com/3/upload.xml", nvc); string res = System.Text.Encoding.Default.GetString(response); var xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(res); info.link = new Uri(xmlDoc.SelectSingleNode("data/link").InnerText); info.deletehash = xmlDoc.SelectSingleNode("data/deletehash").InnerText; info.id = xmlDoc.SelectSingleNode("data/id").InnerText; info.success = true; } catch (Exception e) { info.success = false; info.ex = e; } return info; } }
public void Update() { if (!started) { return; } // Aceptamos conexiones entrantes while (listener.Pending()) { clients.Add(listener.AcceptTcpClient()); } // Ahora leemos de los sockets foreach (TcpClient c in clients) { if (c.Available > 0) { byte[] buffer = new byte[c.Available]; c.GetStream().Read(buffer, 0, c.Available); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(System.Text.UTF8Encoding.GetEncoding(1250).GetString(buffer)); ServiceDispatcher.Instance.Dispatch(c, doc.FirstChild); } } }
public static Xml read(Connection connection) { System.Xml.XmlDocument document = new System.Xml.XmlDocument(); document.LoadXml(connection.stream.readString()); return new Xml(document); }
/// <summary> /// Adjusts for dynamic loading when no entry assembly is available/configurable. /// </summary> /// <remarks> /// When dynamic loading is used, the configuration path from the /// applications entry assembly to the connection setting might be broken. /// This method makes up the necessary configuration entries. /// </remarks> public static void AdjustForDynamicLoad() { if (theObjectScopeProvider1 == null) theObjectScopeProvider1 = new ObjectScopeProvider1(); if (theObjectScopeProvider1.myDatabase == null) { string assumedInitialConfiguration = "<openaccess>" + "<references>" + "<reference assemblyname='PLACEHOLDER' configrequired='True'/>" + "</references>" + "</openaccess>"; System.Reflection.Assembly dll = theObjectScopeProvider1.GetType().Assembly; assumedInitialConfiguration = assumedInitialConfiguration.Replace( "PLACEHOLDER", dll.GetName().Name); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(assumedInitialConfiguration); Database db = Telerik.OpenAccess.Database.Get("DatabaseConnection1", xmlDoc.DocumentElement, new System.Reflection.Assembly[] { dll }); theObjectScopeProvider1.myDatabase = db; } }
public bool UpdateHierarchy() { hierarchy = new Dictionary<string, OneNotePageInfo>(); string hierarchyXmlString = ""; bool success = instance.TryGetHierarchyAsXML(out hierarchyXmlString); if (success) { System.Xml.XmlDocument hierarchyXml = new System.Xml.XmlDocument(); try { hierarchyXml.LoadXml(hierarchyXmlString); } catch (System.Exception exception) { etc.LoggerHelper.LogException(exception); return false; } bool successPageInfos = TryGetOneNotePageInfos(hierarchyXml, out hierarchy); if (successPageInfos) { int totalCount = hierarchy.Count; int i = 0; foreach (KeyValuePair<string, OneNotePageInfo> pageInfo in hierarchy) { i++; string pageId = pageInfo.Key; string pageInnerTextHash = ""; bool successHash = TryGetHashOfOneNotePage(pageId, out pageInnerTextHash); if (successHash) { pageInfo.Value.HashOfInnerText = pageInnerTextHash; pageInfo.Value.IsOkay = true; FireProgressEvent(i, totalCount, pageInfo.Value.PageName); } else { etc.LoggerHelper.LogWarn("Unable to get a hash, pageId:{0}", pageId); } } return true; } else { etc.LoggerHelper.LogWarn("Unable to parse the hierarchy"); return false; } } else { etc.LoggerHelper.LogWarn("Unable to get a hierarchy"); return false; } }
private string ExtractTranslation(string response) { if (response == null) throw new ArgumentNullException(nameof(response)); var xTranslation = new System.Xml.XmlDocument(); xTranslation.LoadXml(response); return xTranslation.InnerText; }
public static System.Xml.XmlDocument Load(string Xml) { var Doc = new System.Xml.XmlDocument(); Doc.LoadXml(Xml); return Doc; }
protected void ComprobantesGridView_RowCommand(object sender, GridViewCommandEventArgs e) { FeaEntidades.InterFacturas.lote_comprobantes lote = new FeaEntidades.InterFacturas.lote_comprobantes(); System.Xml.Serialization.XmlSerializer x; int item = Convert.ToInt32(e.CommandArgument); List<Entidades.Comprobante> lista = (List<Entidades.Comprobante>)ViewState["Comprobantes"]; Entidades.Comprobante comprobante = lista[item]; switch (e.CommandName) { case "Seleccionar": Session["ComprobanteATratar"] = new Entidades.ComprobanteATratar(Entidades.Enum.TratamientoComprobante.Consulta, comprobante); string script = "window.open('/ComprobanteConsulta.aspx', '');"; ScriptManager.RegisterStartupScript(this, typeof(Page), "popup", script, true); break; case "XML": ////Generar Lote //lote = GenerarLote(false); ////Grabar en base de datos //RN.Comprobante c = new RN.Comprobante(); //lote.cabecera_lote.DestinoComprobante = "ITF"; //lote.comprobante[0].cabecera.informacion_comprobante.Observacion = ""; //c.Registrar(lote, null, "ITF", ((Entidades.Sesion)Session["Sesion"])); x = new System.Xml.Serialization.XmlSerializer(lote.GetType()); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(comprobante.Cuit); sb.Append("-"); sb.Append(comprobante.NroPuntoVta.ToString("0000")); sb.Append("-"); sb.Append(comprobante.TipoComprobante.Id.ToString("00")); sb.Append("-"); sb.Append(comprobante.Nro.ToString("00000000")); sb.Append(".xml"); //System.IO.MemoryStream m = new System.IO.MemoryStream(); //System.IO.StreamWriter sw = new System.IO.StreamWriter(m); //sw.Flush(); //System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1")); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(comprobante.Request); xmlDoc.Save(Server.MapPath(@"~/Temp/" + sb.ToString())); //x.Serialize(writerdememoria, xmlDoc); //m.Seek(0, System.IO.SeekOrigin.Begin); //Descarga directa del XML //System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + sb.ToString()), System.IO.FileMode.Create); //m.WriteTo(fs); //fs.Close(); Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + sb.ToString(), false); break; default: break; } }
public void DeserializeEpisodeWithNoAirsAfter() { string xmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Data><Episode><id>181165</id><Combined_episodenumber>1</Combined_episodenumber><Combined_season>0</Combined_season><DVD_chapter></DVD_chapter><DVD_discid></DVD_discid><DVD_episodenumber></DVD_episodenumber><DVD_season></DVD_season><Director></Director><EpImgFlag></EpImgFlag><EpisodeName>Stewie Griffin: The Untold Story (Feature Movie)</EpisodeName><EpisodeNumber>1</EpisodeNumber><FirstAired>2006-05-21</FirstAired><GuestStars></GuestStars><IMDB_ID></IMDB_ID><Language>en</Language><Overview>When Stewie sees a man who looks just like him on TV, he's convinced that he must be his real father. Stewie sets off on a cross-country road trip to find him, but his incredible journey leads to outrageous discoveries.</Overview><ProductionCode></ProductionCode><Rating>7.8</Rating><RatingCount>5</RatingCount><SeasonNumber>0</SeasonNumber><Writer></Writer><absolute_number></absolute_number><airsafter_season></airsafter_season><airsbefore_episode>1</airsbefore_episode><airsbefore_season>5</airsbefore_season><filename>episodes/75978/181165.jpg</filename><lastupdated>1278363452</lastupdated><seasonid>23437</seasonid><seriesid>75978</seriesid><thumb_added></thumb_added><thumb_height>223</thumb_height><thumb_width>300</thumb_width></Episode></Data>"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(xmlContent); System.Xml.XmlNode dataNode = doc.ChildNodes[1]; System.Xml.XmlNode episodeNode = dataNode.ChildNodes[0]; Episode target = new Episode(); target.Deserialize(episodeNode); string expectedGuestStars = null; string expectedOverview = "When Stewie sees a man who looks just like him on TV, he's convinced that he must be his real father. Stewie sets off on a cross-country road trip to find him, but his incredible journey leads to outrageous discoveries."; string expectedWriter = null; Assert.Equal(181165, target.Id); Assert.Equal(1.0, target.CombinedEpisodeNumber); Assert.Equal(0, target.CombinedSeason); Assert.Equal(-1, target.DVDChapter); Assert.Equal(-1, target.DVDDiscId); Assert.Equal(-1.0, target.DVDEpisodeNumber); Assert.Equal(-1, target.DVDSeason); Assert.Equal(null, target.Director); Assert.Equal(-1, target.EpImageFlag); Assert.Equal("Stewie Griffin: The Untold Story (Feature Movie)", target.Name); Assert.Equal(1, target.Number); Assert.Equal(new DateTime(2006, 5, 21, 0, 0, 0), target.FirstAired); Assert.Equal(expectedGuestStars, target.GuestStars); Assert.Equal(null, target.IMDBId); Assert.Equal("en", target.Language); Assert.Equal(expectedOverview, target.Overview); Assert.Equal(-1, target.ProductionCode); Assert.Equal(7.8, target.Rating); Assert.Equal(0, target.SeasonNumber); Assert.Equal(expectedWriter, target.Writer); Assert.Equal(-1, target.AbsoluteNumber); Assert.Equal("episodes/75978/181165.jpg", target.PictureFilename); Assert.Equal(1278363452, target.LastUpdated); Assert.Equal(23437, target.SeasonId); Assert.Equal(75978, target.SeriesId); Assert.Equal(5, target.RatingCount); Assert.Equal(0, target.Thumbadded); Assert.Equal(223, target.ThumbHeight); Assert.Equal(300, target.ThumbWidth); Assert.Equal(false, target.IsTMSExport); Assert.Equal(false, target.IsTMSReviewBlurry); Assert.Equal(-1, target.TMSReviewById); Assert.Equal(false, target.IsTMSReviewDark); Assert.Equal(DateTime.MinValue, target.TMSReviewDate); Assert.Equal(-1, target.TMSReviewLogoId); Assert.Equal(-1, target.TMSReviewOther); Assert.Equal(false, target.IsTMSReviewUnsure); Assert.Equal(-1, target.AirsAfterSeason); Assert.Equal(1, target.AirsBeforeEpisode); Assert.Equal(5, target.AirsBeforeSeason); }
public void CreateForumForGroup(int PortalId, int ModuleId, int SocialGroupId, string Config) { var xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(Config); { System.Xml.XmlNode xRoot = xDoc.DocumentElement; System.Xml.XmlNodeList xNodeList = xRoot.SelectNodes("//defaultforums/groups/group"); } }
public static AtomFeed LoadXML(string xml) { var dom = new System.Xml.XmlDocument(); var nsmgr = new System.Xml.XmlNamespaceManager(dom.NameTable); nsmgr.AddNamespace(NamespaceShortName, NamespaceURI); dom.LoadXml(xml); var feed = load_from_dom(dom, nsmgr); return feed; }
public static RetEntity Parse(string ret) { var entity = new RetEntity(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(ret); entity.Result = doc.DocumentElement.GetAttribute("result"); entity.Method = doc.DocumentElement.GetAttribute("name"); foreach (System.Xml.XmlNode node in doc.SelectNodes("//Item")) { entity.Messages.Add(Message.Parse(node)); }; return entity; }
public static Microsoft.Samples.FeedSync.Feed CreateFeedFromURL(string i_Url) { // Get the feed from URL: string strFeed = Microsoft.Samples.FeedSyncService.FeedManager.ReadFeedContents(i_Url); // Create a new XML document instance for the feed System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(strFeed); // Create a Feed object to read and manipulate feed items return Microsoft.Samples.FeedSync.Feed.Create(xmlDoc); }
/// <summary> /// On startup, make sure that the blog script is added to Rendition.js. /// </summary> private void initializing(object sender, EventArgs e) { Admin.AddUIScript(GetResourceString("BlogEditor.js")); Admin.AddUIScript(GetResourceString("GalleryEditor.js")); Admin.AddUIScript(GetResourceString("Ui_init.js")); Galleries = new Galleries(Site.CurrentSite); Blogs = new Blogs(Site.CurrentSite); // add localization System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(GetResourceString("Localization.xml")); FieldTitleLocalization.AddXMLSource(xmlDoc); }
// GET: Encuesta public ActionResult ListSubFamilia(string iddet, string finalizada) { //Cargo variable encuesta ID & Respuestas ini if (Session["ENCUESTA_ID"] == null) { Session["ENCUESTA_ID"] = iddet; } var data = new List<Encuesta>(); if (TempData["ListSubFamilia"] == null) { //XMLReader readXML = new XMLReader(); //data = readXML.RetrunListOfSubFamilia(iddet); System.Xml.XmlDocument xDocumento = new System.Xml.XmlDocument(); ServiceITLProxy.ServiceITL obj = new ServiceITLProxy.ServiceITL(); var sRespuesta = obj.SubFamilia(iddet); if (sRespuesta != null) { xDocumento.LoadXml(sRespuesta); XMLReader readXML = new XMLReader(); data = readXML.ReturnListOfSubFamilia(xDocumento); //ViewBag.contadorSE = data.Count; Session["contadorSE"] = data.Count; TempData["ListSubFamilia"] = data; } } else { data = TempData["ListSubFamilia"] as List<Encuesta>; TempData.Keep("ListSubFamilia"); } //inicializa datos de SubFamilia var myEnc = data.ToList(); var found = myEnc.FirstOrDefault(c => c.ID_ENCUESTA_SUB == iddet); if (found != null) { found.Finalizada = "S"; } return View(data.ToList()); }
public String Process(String ReqXml) { String ResXml = string.Empty; string ReqCode = string.Empty; try { com.individual.helper.LogNet4.WriteMsg(ReqXml); System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.LoadXml(ReqXml); //待验证数据 string MsgData = xmldoc.SelectSingleNode("JTW91G/MsgData").OuterXml; //数字签名 string Signature = xmldoc.SelectSingleNode("JTW91G/SignData/Signature").InnerText; //RSA公钥 string RsaPubKey = xmldoc.SelectSingleNode("JTW91G/SignData/RsaPubKey").InnerText; //请求指令 ReqCode = xmldoc.SelectSingleNode("JTW91G/MsgData/ReqHeader/ReqCode").InnerText; if (com.individual.helper.RsaSha1Helper.verify(MsgData, RsaPubKey, Signature)) { //系统类型 string OsType = xmldoc.SelectSingleNode("JTW91G/MsgData/ReqHeader/OsType").InnerText; if (string.IsNullOrEmpty(OsType) || ("0" != OsType && "1" != OsType && "2" != OsType)) { return GssResXml.GetResXml(ReqCode, ResCode.UL037, ResCode.UL037Desc, string.Format("<DataBody></DataBody>")); } //反射出具体的实现类 Type t = Type.GetType("JtwPhone.Code." + ReqCode); //获取方法 System.Reflection.MethodInfo minfo = t.GetMethod("AnalysisXml"); //执行方法 ResXml = minfo.Invoke(System.Activator.CreateInstance(t), new Object[] { ReqXml }).ToString(); } else //验证签名失败 { ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL006, ResCode.UL006Desc, string.Format("<DataBody></DataBody>")); } } catch (Exception ex) { com.individual.helper.LogNet4.WriteErr(ex); //业务处理失败 ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL005, ResCode.UL005Desc, string.Format("<DataBody></DataBody>")); } return ResXml; }
/// <summary> /// Runs once per site startup. Loads all the .js files onto the back /// of the Rendition.js file using the Rendition.Main.UIScripts.Add() method. /// </summary> void Site_Initializing(object sender, EventArgs e) { // add scripts string[] files = { "Aging.js", "InventoryEditor.js", "ProductionAging.js", "ProductionPicklist.js", "SalesJournal.js","Ui_init.js" }; foreach(string file in files) { Admin.AddUIScript(GetResourceString(file)); } // add localization System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(GetResourceString("Localization.xml")); FieldTitleLocalization.AddXMLSource(xmlDoc); }
public IList<Template> GetTemplates() { IList<Template> list = new List<Template>(); Directory.GetDirectories(WebPathManager.TemplateUrl).ToList().ForEach(s => { string dir = string.Format("{0}{1}\\", WebPathManager.TemplateUrl, s); var xml = new System.Xml.XmlDocument(); xml.LoadXml(string.Format("{0}config.xml", dir)); var node = xml.GetElementsByTagName("template")[0]; list.Add(new Template { Name = node.Attributes["name"].Value, Url = dir, ContentUrl = node.Attributes["contentfolder"].Value, TempImage = this.GetTempImage(dir, s) }); }); return list; }
public BoundsPicker(string bounds, string[] coordsys) : this() { m_bounds = bounds; if (coordsys == null) { SRSLabel.Visible = SRSCombo.Visible = false; this.Height -= 30; } else SRSCombo.Items.AddRange(coordsys); if (!string.IsNullOrEmpty(bounds)) { try { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); if (bounds.Trim().StartsWith("<")) //NOXLATE bounds = System.Web.HttpUtility.HtmlDecode(bounds); bounds = "<root>" + bounds + "</root>"; //NOXLATE doc.LoadXml(bounds); System.Xml.XmlNode root = doc["root"]; //NOXLATE if (root["Bounds"] != null) //NOXLATE { if (root["Bounds"].Attributes["SRS"] != null) //NOXLATE SRSCombo.Text = root["Bounds"].Attributes["SRS"].Value; //NOXLATE if (root["Bounds"].Attributes["west"] != null) //NOXLATE MinX.Text = root["Bounds"].Attributes["west"].Value; //NOXLATE if (root["Bounds"].Attributes["east"] != null) //NOXLATE MaxX.Text = root["Bounds"].Attributes["east"].Value; //NOXLATE if (root["Bounds"].Attributes["south"] != null) //NOXLATE MinY.Text = root["Bounds"].Attributes["south"].Value; //NOXLATE if (root["Bounds"].Attributes["north"] != null) //NOXLATE MaxY.Text = root["Bounds"].Attributes["north"].Value; //NOXLATE } else throw new Exception(Strings.BoundsPicker_MissingBoundsError); } catch(Exception ex) { string msg = NestedExceptionMessageProcessor.GetFullMessage(ex); MessageBox.Show(this, string.Format(Strings.BoundsPicker_BoundsDecodeError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public Location GeocodeLocation(string address) { var url = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=" + System.Web.HttpUtility.UrlEncode(address); var xmlString = _client.DownloadString(url); var xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(xmlString); var loc = new Location(); loc.Latitude = Double.Parse(xmlDoc.SelectSingleNode("//geometry/location/lat").InnerText, NumberFormatInfo.InvariantInfo); loc.Longitude = double.Parse(xmlDoc.SelectSingleNode("//geometry/location/lng").InnerText, NumberFormatInfo.InvariantInfo); return loc; }
public static string[] GetArrayVal(string xml, string xpath, bool isGetXml) { System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.LoadXml(xml); System.Xml.XmlNodeList xnl = xd.SelectNodes(xpath); List<string> list = new List<string>(); if (xnl.Count > 0) { foreach (System.Xml.XmlNode xn in xnl) { list.Add(isGetXml ? xn.InnerXml : xn.InnerText); } } return list.ToArray(); }
/// <summary> /// Process the data and generates ONE string for each message enclosed in <_packetTag></_packetTag> /// </summary> /// <param name="xmlData">XML String to process</param> protected virtual ArrayList ProcessData(string xmlData) { ArrayList col = new ArrayList(); // Do a search of nodes <_packetTag> // Format of a document is one root node of and System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(xmlData); _packetInfo = null; //System.Xml.XmlNode packetNode = doc.SelectSingleNode("//" + _packetTag); System.Xml.XmlNode packetNode = doc.FirstChild; //if (packetNode != null) if (packetNode.LocalName.Equals(_packetTag)) { // Gets the childs of the node foreach (System.Xml.XmlNode node in packetNode.ChildNodes) { col.Add(node.OuterXml); } // Gets the atributes of the packetNode System.Xml.XmlAttributeCollection attrs = packetNode.Attributes; if (attrs != null) { string dtx = null; string src = null; foreach (System.Xml.XmlAttribute attr in attrs) { if (attr.Name.Equals("dtx")) { dtx = attr.Value; } else if (attr.Name.Equals("src")) { src = attr.Value; } } _packetInfo = new PacketData(dtx, src); } } return(col); }
/* * private static void ProcessXml(ref string xmlString) * { * using (var reader = System.Xml.XmlReader.Create(new StringReader(xmlString))) * { * reader.ReadToFollowing("urlBase"); * xmlString = reader.ReadElementContentAsString(); * } * } */ private static BingImage GetImageData(string xmlString) { var newImage = new BingImage(); System.Xml.XmlDocument data = new System.Xml.XmlDocument(); data.LoadXml(xmlString); var imageDta = data.GetElementsByTagName("image"); foreach (System.Xml.XmlNode node in imageDta[0].ChildNodes) { var value = node.InnerText; switch (node.Name.ToUpperInvariant()) { case "STARTDATE": var year = Convert.ToInt32(value.Substring(0, 4), CultureInfo.InvariantCulture); var mon = Convert.ToInt32(value.Substring(4, 2), CultureInfo.InvariantCulture); var date = Convert.ToInt32(value.Substring(6, 2), CultureInfo.InvariantCulture); newImage.ImageDate = new DateTime(year, mon, date); break; case "URLBASE": newImage.Url = value; break; case "COPYRIGHT": newImage.Copyright = value; break; case "HEADLINE": newImage.Title = value; break; case "COPYRIGHTLINK": newImage.Comment = value; break; } } return(newImage); }
private TResponse Request <TRequest, TResponse>(TRequest request, Uri uri) where TRequest : Data.Request where TResponse : Data.Response, new() { if (request == null) { throw new ArgumentNullException("request"); } request.sign = Config.Signature(request); var xml = Util.XmlSerializer.Serialize(request).InnerXml; var handler = new System.Net.Http.HttpClientHandler { ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Manual, UseDefaultCredentials = false }; handler.ClientCertificates.Add(Certificate); string content; using (var client = new System.Net.Http.HttpClient(handler)) { var response = client.PostAsync(uri, new System.Net.Http.StringContent(xml, Encoding.UTF8)).Result; content = response.Content.ReadAsStringAsync().Result; } var dom = new System.Xml.XmlDocument(); dom.LoadXml(content); var result = Util.XmlSerializer.Deserialize <TResponse>(dom); if (result.return_code == "FAIL") { throw new WechatException(result.return_msg); } if (result.result_code == "FAIL") { throw new WechatBusinessException(result.err_code, result.err_code_des); } return(result); }
public ContentSlide(int SlideSerial) { _SlideSerial = SlideSerial; using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString)) { string SQL = "SELECT [ModuleID], [SlideTitle], [SlideContents], [SlideImage], [SlideLink], [SortOrder] " + "FROM [cms_Slideshow] " + "WHERE SlideSerial = @SlideSerial"; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("SlideSerial", SqlDbType.Int).Value = SlideSerial; cmd.Connection.Open(); SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow); if (dr.HasRows) { dr.Read(); _ModuleID = dr.GetGuid(0); _SlideTitle = dr[1].ToString(); _SlideContents = dr[2].ToString(); _SlideImage = dr[3].ToString(); _SlideLink = dr[4].ToString(); _SortOrder = dr.GetInt32(5); } cmd.Connection.Close(); } if (!string.IsNullOrEmpty(_SlideImage)) { ImageSaveModel imageSaveModel = new ImageSaveModel(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(_SlideImage); System.Xml.XmlNodeReader reader = new System.Xml.XmlNodeReader(doc.DocumentElement); System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(imageSaveModel.GetType()); imageSaveModel = (ImageSaveModel)ser.Deserialize(reader); _SlideImageFile = imageSaveModel.Src; _DimHeight = Convert.ToInt32(imageSaveModel.Height); _DimWidth = Convert.ToInt32(imageSaveModel.Width); } } }
public void loadConfigFile() { xmlconfigerror = false; try { defaultXMLConfig = GetResourceTextFile("CSLStatsPanelConfig.xml"); defaultXMLConfigVersion = getXMLConfigVersion(defaultXMLConfig); string mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (System.IO.File.Exists(mydocs + "\\CSLStatsPanel\\CSLStatsPanelConfig.xml")) { defaultXMLConfig = System.IO.File.ReadAllText(mydocs + "\\CSLStatsPanel\\CSLStatsPanelConfig.xml"); try { System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument(); xdoc.LoadXml(defaultXMLConfig); } catch { xmlconfigerror = true; defaultXMLConfig = GetResourceTextFile("CSLStatsPanelConfig.xml"); } loadedXMLConfigVersion = getXMLConfigVersion(defaultXMLConfig); } else { loadedXMLConfigVersion = defaultXMLConfigVersion; } loadConfigSettings(defaultXMLConfig); } catch (Exception ex) { statlog.log("loadConfigfile: " + ex.Message); loadedXMLConfigVersion = defaultXMLConfigVersion; } finally { } }
public static bool ExecuteXml(string sqlSpName, SqlParameter[] dbParams, System.Xml.XmlDocument dXml) { SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings.Get("connectionString")); SqlCommand cmd = new SqlCommand(sqlSpName, cn); cmd.CommandTimeout = Convert.ToInt16(ConfigurationManager.AppSettings.Get("connectionCommandTimeout")); cmd.CommandType = CommandType.StoredProcedure; if (dbParams != null) { foreach (SqlParameter dbParam in dbParams) { cmd.Parameters.Add(dbParam); } } cn.Open(); bool bReturn; try { //dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (dr.Read()) { System.Data.SqlTypes.SqlXml oXml = dr.GetSqlXml(dr.GetOrdinal("Xml")); dXml.LoadXml(oXml.Value); bReturn = true; } else { bReturn = false; } } } catch (Exception) { throw; } return(bReturn); }
private static ThreeDSecuredCreditCard Verify3D_Saferpay(ThreeDSecuredCreditCard threeDCard) { ThreeDSecuredCreditCard result3DCard = new ThreeDSecuredCreditCard(); result3DCard = threeDCard; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(threeDCard.PaRes); System.Xml.XmlElement root = doc.DocumentElement; string authenticationResult = (null != root && root.HasAttribute("RESULT")) ? root.Attributes["RESULT"].Value : string.Empty; string mpiSessionId = (null != root && root.HasAttribute("MPI_SESSIONID")) ? root.Attributes["MPI_SESSIONID"].Value : string.Empty; string authenticationMessage = (null != root && root.HasAttribute("MESSAGE")) ? root.Attributes["MESSAGE"].Value : string.Empty; string authenticationType = (null != root && root.HasAttribute("MSGTYPE")) ? root.Attributes["MSGTYPE"].Value : string.Empty; string eci = (null != root && root.HasAttribute("ECI")) ? root.Attributes["ECI"].Value : string.Empty; result3DCard.ReasonCode = !string.IsNullOrEmpty(authenticationResult) ? authenticationResult : threeDCard.ReasonCode; result3DCard.Decision = !string.IsNullOrEmpty(authenticationMessage) ? authenticationMessage : threeDCard.Decision; result3DCard.Eci = !string.IsNullOrEmpty(eci) ? eci : threeDCard.Eci; // 3D popup response data is good, then call Verify3DAuthentication(...) if (authenticationType == "AuthenticationConfirm" && authenticationResult == "0") { bool callVerificationService = true; if (HLConfigManager.Configurations.PaymentsConfiguration.Check3DPaymentEci && eci != "1" && eci != "2") { callVerificationService = false; result3DCard.IsErrored = true; } if (callVerificationService) { result3DCard = ThreeDPaymentProvider.Verify3DThroughSevice(result3DCard); } } else { result3DCard.IsErrored = true; } return(result3DCard); }
public static bool ExecuteXml(string sqlSpName, SqlParameter[] dbParams, System.Xml.XmlDocument dXml) { SqlConnection cn = new SqlConnection("Data Source=(local);Initial Catalog=ServicioImpresion;Integrated Security=True"); SqlCommand cmd = new SqlCommand(sqlSpName, cn); cmd.CommandTimeout = Convert.ToInt16("10000"); cmd.CommandType = CommandType.StoredProcedure; if (dbParams != null) { foreach (SqlParameter dbParam in dbParams) { cmd.Parameters.Add(dbParam); } } cn.Open(); bool bReturn; try { //dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (dr.Read()) { System.Data.SqlTypes.SqlXml oXml = dr.GetSqlXml(dr.GetOrdinal("Xml")); dXml.LoadXml(oXml.Value); bReturn = true; } else { bReturn = false; } } } catch (Exception) { throw; } return(bReturn); }
public void typesFile() { if (!File.Exists(this.dataDir + "types.xml")) { System.Xml.XmlDocument newDoc = new System.Xml.XmlDocument(); string sTextX = "<types>"; sTextX += "<type>"; sTextX += "<tnamn></tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Timme</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Timmar</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Styck</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>m²</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Kartong</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Enhet</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Enheter</tnamn>"; sTextX += "</type>"; sTextX += "<type>"; sTextX += "<tnamn>Kilo</tnamn>"; sTextX += "</type>"; sTextX += "</types>"; newDoc.LoadXml(sTextX); newDoc.PrependChild(newDoc.CreateXmlDeclaration("1.0", "utf-8", "")); newDoc.Save(this.dataDir + @"types.xml"); } }
static void Main1() { Heater heater = new Heater(); Alarm alarm = new Alarm(); //heater.Boiled += alarm.MakeAlert; //注册方法 //heater.Boiled += (new Alarm()).MakeAlert; //给匿名对象注册方法 heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); //也可以这么注册 heater.Boiled += Display.ShowMsg; //注册静态方法 heater.BoilWater(); //烧水,会自动调用注册过对象的方法 Console.Write(TicketType.MasterCookieName.ToString() == "MasterCookieName"); string xml = "<xml><row><AreaId>1</AreaId></row><row><AreaId>2</AreaId></row><row><AreaId>3</AreaId></row></xml>"; System.Xml.XmlDocument xmlString = new System.Xml.XmlDocument(); xmlString.LoadXml(xml); IList <CityBase> city = new List <CityBase>(); CityBase model = new CityBase(); model.CityName = "A"; model.ID = 1; CityBase model1 = new CityBase(); model.CityName = "B"; model.ID = 2; city.Add(model); city.Add(model1); IList <CityBase> city2 = city.Where(item => (item.ID == 2 && item.CityName == "C")).ToArray(); Console.Write(city2.Count); Console.Read(); }
private void btVerifyData_Click(object sender, System.EventArgs e) { try { System.Xml.XmlDocument xmlSigned = new System.Xml.XmlDocument(); xmlSigned.LoadXml(txtSignedXml2.Text); if (DevAge.Security.Cryptography.Utilities.XmlDigitalSign.CheckSignature(xmlSigned, txtPubKey.Text)) { MessageBox.Show(this, "Signature OK"); } else { MessageBox.Show(this, "Signature FAILED"); } } catch (Exception ex) { MessageBox.Show(this, ex.Message); } }
private List <Point> GetRoadRegionFromXML(string xml) { List <Point> ret = new List <Point>(); if (string.IsNullOrEmpty(xml)) { return(ret); } System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.LoadXml(xml); System.Xml.XmlNode item = xmldoc.SelectSingleNode("root/AlgorithmInitParam/RoadRegion/RoadInfo"); List <System.Drawing.Point> RegionPointList = new List <System.Drawing.Point>(); foreach (System.Xml.XmlNode it in item.SelectNodes("PointSet/Point")) { RegionPointList.Add(new System.Drawing.Point(Convert.ToInt32(it.SelectSingleNode("X").InnerText), Convert.ToInt32(it.SelectSingleNode("Y").InnerText))); } ret = RegionPointList; return(ret); }
public static void Test() { string xml = @" <root> <foo /> <foo> <bar attr='value'/> <bar other='va' /> </foo> <foo><bar /></foo> </root>"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(xml); System.Xml.XmlNode node = doc.SelectSingleNode("//@attr"); string xpath = FindXPath(node); System.Console.WriteLine(xpath); System.Console.WriteLine(doc.SelectSingleNode(xpath) == node); } // End Sub Test
ParseArtifactNamesAndVersionsFromXML ( string xml ) { System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.LoadXml(xml); System.Xml.XmlNamespaceManager ns = new System.Xml.XmlNamespaceManager(xmldoc.NameTable); System.Xml.XmlNodeList node_list = xmldoc.SelectNodes($"/{this.Name}/*", ns); foreach (System.Xml.XmlNode xn in node_list) { string n = xn.Name; string[] vs = xn.Attributes["versions"].InnerXml.Split ( new string[] { "," }, StringSplitOptions.RemoveEmptyEntries ); yield return(name : n, versions : vs); } }
public string GetOriginalChain(string stringXML, string XSLTFile) { StringWriter sw = new StringWriter(); try { System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load(XSLTFile); System.Xml.XmlDocument FromXmlFile = new System.Xml.XmlDocument(); FromXmlFile.LoadXml(stringXML); xslt.Transform(FromXmlFile, null, sw); } catch (Exception ex) { throw new Exception("No se pudo generar la cadena", ex.InnerException); } return(sw.ToString()); }
private void GetAccidentFromXML(string xml, out bool checkJam, out int jamNum, out int jamTime) { if (string.IsNullOrEmpty(xml)) { checkJam = false; jamNum = 10; jamTime = 20; return; } System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument(); xmldoc.LoadXml(xml); System.Xml.XmlNode checkJamNode = xmldoc.SelectSingleNode("root/AlgorithmInitParam/Accident/CheckJam/Enable"); checkJam = Convert.ToBoolean(checkJamNode.InnerText); System.Xml.XmlNode jamNumNode = xmldoc.SelectSingleNode("root/AlgorithmInitParam/Accident/CheckJam/NumJamThresh"); jamNum = Convert.ToInt32(jamNumNode.InnerText); System.Xml.XmlNode jamTimeNode = xmldoc.SelectSingleNode("root/AlgorithmInitParam/Accident/CheckJam/TimeJamThresh"); jamTime = Convert.ToInt32(jamTimeNode.InnerText); }
/// <summary> /// 将短信接口状态转换为系统状态 /// </summary> /// <param name="str">短信接口状态</param> /// <returns>系统状态</returns> private SmsResult GetResult(string str) { SmsResult result = new SmsResult(); System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.LoadXml(str); string retCode = xml["ROOT"]["RetCode"].InnerText; if (retCode.ToLower() == "faild") { result.Status = SmsResultStatus.Failue; result.RowCount = 0; } else { result.Status = SmsResultStatus.Success; result.RowCount = int.Parse(xml["ROOT"]["OKPhoneCounts"].InnerText); } return(result); }
public void LoadXml(string xml) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); try { doc.LoadXml(xml); XmlHeader = new VXmlHeader(this, doc.FirstChild); NodeRoot = new VXmlNode(this); NodeRoot.Init(doc.DocumentElement); m_sFile = ""; NCalc = true; } catch (System.Exception ex) { MessageBox.Show("读取XML字符串失败,请确认xml字符串是否正确。\n" + ex.Message); } }
public void Serialize_MatchPatternWithNumericFormat_NumericFormatButNoOtherElement() { var matchPattern = new MatchPatternXml(); matchPattern.NumericFormat.DecimalDigits = 2; var manager = new XmlManager(); var str = manager.XmlSerializeFrom <MatchPatternXml>(matchPattern); var xml = new System.Xml.XmlDocument(); xml.LoadXml(str); var node = xml.ChildNodes[1]; Assert.That(node.ChildNodes[0].Name, Is.EqualTo("numeric-format")); Assert.That(node.ChildNodes[0].Attributes["decimal-digits"], Is.Not.Null); Assert.That(node.ChildNodes[0].Attributes["decimal-digits"].Value, Is.EqualTo("2")); Assert.That(node.ChildNodes, Has.Count.EqualTo(1)); Assert.That(node.ChildNodes[0].Attributes, Has.Count.EqualTo(1)); }
static void Main(string[] args) { string xml = System.IO.File.ReadAllText(@"c:\tmp\person.xml"); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(xml); List <Person> lst = new List <Person>(); // alle personer var personer = doc.SelectNodes("//person"); foreach (System.Xml.XmlNode item in personer) { int id = Convert.ToInt32(item.Attributes["id"].Value); string navn = item.SelectSingleNode("navn").InnerText; int alder = Convert.ToInt32(item.SelectSingleNode("alder").InnerText); lst.Add(new Person { Id = 1, Navn = navn, Alder = alder }); } lst.ForEach(i => Console.WriteLine(i.Navn)); }
public void GetSearch() { string url = string.Format("http://search.hatena.ne.jp/keyword?word=兵庫県&mode=rss&ie=utf8&page=1"); HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse webRes = (HttpWebResponse)webReq.GetResponse()) { Stream stream = webRes.GetResponseStream(); using (StreamReader reader = new StreamReader(stream)) { string str = reader.ReadToEnd(); System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument(); xdoc.LoadXml(str); Console.WriteLine(str); Console.WriteLine("==========================================="); System.Xml.XmlNode root = xdoc["rdf:RDF"]; System.Xml.XmlNode item = root["item"]; Console.WriteLine(item["description"].InnerText); } } }
/// <summary> /// 创建配置文件app.config /// </summary> /// <param name="dbname"></param> /// <param name="databasename"></param> private void CreateXml(string dbname, string databasename) { string oldb = @"|DataDirectory|\App_Data\SpiderResult.mdb"; StringBuilder strxml = new StringBuilder(); strxml.Append("<configuration>"); strxml.Append("<configSections></configSections>"); strxml.Append("<connectionStrings>"); strxml.Append("<add name=\"connectionstring\" connectionString=\"Data Source=" + dbname + ";Initial Catalog=" + databasename + ";User ID=sa;Pwd=sa;\" providerName=\"System.Data.SqlClient\" />"); strxml.Append("<add name=\"Wyc_UI.Properties.Settings.SpiderResultConnectionString\" connectionString=\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + oldb + ";Persist Security Info=True\" providerName=\"System.Data.OleDb\" />"); strxml.Append("</connectionStrings>"); strxml.Append("<startup>"); strxml.Append("<supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.0\"/>"); strxml.Append("</startup>"); strxml.Append("</configuration>"); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(strxml.ToString()); doc.Save(@"App.config"); //doc.Save(@"XT_GNB.xml"); //doc.Save(Server.MapPath("~/XT_GNB.xml")); }
/// <summary> /// 将短信接口状态转换为系统状态 /// </summary> /// <param name="str">短信接口状态</param> /// <returns>系统状态</returns> private SmsResult GetResult(string str) { SmsResult result = new SmsResult(); System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.LoadXml(str); string retCode = xml["SubmitResult"]["code"].InnerText; if (retCode.ToLower() != "2") { result.Status = SmsResultStatus.Failue; result.RowCount = 0; } else { result.Status = SmsResultStatus.Success; result.RowCount = int.Parse(xml["SubmitResult"]["smsid"].InnerText); } return(result); }
private ErrorMsg GetErrorMsg(string rsp) { if (string.IsNullOrEmpty(rsp)) { return new ErrorMsg() { Result = 1, ResultDescription = "无此消息", } } ; System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument(); xdoc.LoadXml(rsp); ErrorMsg err = new ErrorMsg() { Result = Convert.ToUInt32(xdoc.SelectSingleNode("//root/head/code").InnerText), ResultDescription = xdoc.SelectSingleNode("//root/head/message").InnerText, }; return(err); }
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response) { var text = response.Content.ReadAsStringAsync().Result; if (text.Length > 0 && text[0] == '<') { var document = new System.Xml.XmlDocument(); document.LoadXml(text); text = Newtonsoft.Json.JsonConvert.SerializeXmlNode(document, Newtonsoft.Json.Formatting.None); var headers = response.Content.Headers; var enumerator = headers.ContentEncoding?.GetEnumerator(); enumerator?.MoveNext(); var encoding = enumerator?.Current ?? "UTF-8"; response.Content = new System.Net.Http.StringContent( text, System.Text.Encoding.GetEncoding(encoding), headers.ContentType.MediaType); } }
public ActionResult ajxPreviewTemplate(string tempName) { InvTemplate it = new InvTemplate(); IInvTemplateService _invTempSrc = IoC.Resolve <IInvTemplateService>(); it = _invTempSrc.GetByName(tempName); System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument(); xdoc.PreserveWhitespace = true; xdoc.LoadXml(it.XmlFile); System.Xml.XmlProcessingInstruction newPI; String PItext = "type='text/xsl' href='" + FX.Utils.UrlUtil.GetSiteUrl() + "/InvoiceTemplate/GetXSLTbyTempName?tempname=" + it.TemplateName + "'"; newPI = xdoc.CreateProcessingInstruction("xml-stylesheet", PItext); xdoc.InsertBefore(newPI, xdoc.DocumentElement); logtest.Info("tempName: " + tempName + " href: " + PItext); //IViewer _iViewerSrv = IoC.Resolve<IViewer>(); IViewer _iViewerSrv = InvServiceFactory.GetViewer(tempName); return(Json(_iViewerSrv.GetHtml(System.Text.Encoding.UTF8.GetBytes(xdoc.OuterXml)))); }
internal PropertySet PsFromXml(string Xml) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(Xml); //System.Xml.XmlTextReader r =new System.Xml.XmlTextReader(Xml, PropertySet ps = new PropertySet(); //ps.PsValue = Xml; //System.Xml.XmlWriter w = System.Xml.XmlWriter.Create( //System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //doc.LoadXml(Xml); System.Xml.XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "UTF-8", ""); doc.InsertBefore(decl, doc.DocumentElement); ps.PsValue = doc.OuterXml; /* ps.PsValue = @"<?xml version='1.0' encoding='UTF-16'?><?Siebel-Property-Set EscapeNames='true'?><AAA>aaa</AAA>"; * ps.PsValue = @"<?xml version='1.0' encoding='UTF-16'?><AAA>aaa</AAA>"; */ ps = InvokeMethod(m_mainBsName, m_FuncXml2PsName, ps).FunctionResult; return(ps); }
public void SetAttendanceRecordExtendData(string FieldName, string Value) { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); if (string.IsNullOrEmpty(AttendanceRecordExtendData)) { System.Xml.XmlElement rootNode = xmlDoc.CreateElement("AttendanceRecordExtendData"); xmlDoc.AppendChild(rootNode); } else { xmlDoc.LoadXml(AttendanceRecordExtendData); } if (!Value.Equals(string.Empty)) { System.Xml.XmlElement xmlElement = xmlDoc.CreateElement(FieldName); xmlElement.InnerText = Value.Trim(); xmlDoc.DocumentElement.AppendChild(xmlElement); AttendanceRecordExtendData = xmlDoc.InnerXml; } }
private void buttonDoFilter_Click(object sender, EventArgs e) { try { var xml = new System.Xml.XmlDocument(); xml.LoadXml(textBoxExInput.Text); var xnm = new System.Xml.XmlNamespaceManager(xml.NameTable); var result = xml.SelectNodes(comboBoxXPath.Text, xnm); textBoxExOutput.Text = string.Join("\r\n\r\n--------------------\r\n\r\n", result.Cast <System.Xml.XmlNode>().Select(f => FormatXmlDocument(f.OuterXml))); if (textBoxExOutput.Text.Length == 0) { textBoxExOutput.Text = "No results."; } } catch (System.Exception ex) { textBoxExOutput.Text = string.Format("[{0}]\r\n{1}", ex.GetType().Name, ex.Message); } }
public string GetUserLogin(string xml) { string ret = "user"; try { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //creation d'une instance xml doc.LoadXml(xml); //chargement de la variable foreach (System.Xml.XmlNode node in doc.DocumentElement.ChildNodes) { if (node.Name.ToLower() == "username") { ret = node.InnerText; } } } catch (Exception) { } return(ret); }