/// <summary> /// Constructs the Arcs using Xml /// </summary> /// <param name="vsXml">Xml data</param> public Arcs(string vsXml) { XmlTextReader reader = new XmlTextReader(new StringReader(vsXml)); reader.Read(); ArcType = (EnumArcType)Enum.Parse(typeof(EnumArcType), reader.GetAttribute("arctype")); moArcList = new List<Arc>(); while (reader.Read()) { switch (reader.Name) { case "Arcs" : if (reader.NodeType != XmlNodeType.EndElement) { if (moInnerArcs == null) { moInnerArcs = new List<Arcs>(); } moInnerArcs.Add(new Arcs(reader.ReadOuterXml())); } break; case "Arc" : moArcList.Add(new Arc(reader.ReadOuterXml())); break; } } }
private void Listen(object sender, DoWorkEventArgs e) { string url = @"http://" + _ipAddr.ToString() + "/PSIA/Metadata/stream?AreaControlEvents=true"; credentialCache.Add(new System.Uri(url), "Basic", _credentials); _req = WebRequest.Create(url); _req.Credentials = credentialCache; _req.PreAuthenticate = true; HttpWebResponse response = (HttpWebResponse)_req.GetResponse(); Stream responseStream = response.GetResponseStream(); XmlTextReader reader = new XmlTextReader(responseStream); while (true) { reader.MoveToContent(); string contents = reader.ReadOuterXml(); if (OnEventRaised != null) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerAsync(contents); } reader.ResetState(); } }
public EDRMEntity DeserializeEdrmXml(string filePath) { // create an xml reader. XmlReader reader = new XmlTextReader(new FileStream(filePath, FileMode.Open)); // read through elements while (reader.Read()) { // parse document elements. if (reader.Name.Equals("document", StringComparison.InvariantCultureIgnoreCase)) { edrmEntity.BatchEntity.DocumentEntity.Add(ParseEdrmDocumentXml(reader.ReadOuterXml())); } if (reader.Name.Equals("relationship", StringComparison.InvariantCultureIgnoreCase)) { edrmEntity.BatchEntity.Relationships.Add(new RelationshipEntity() { Type = reader.SafeGetAttribute("Type"), ParentDocID = reader.SafeGetAttribute("ParentDocId"), ChildDocID = reader.SafeGetAttribute("ChildDocId") }); } } return edrmEntity; }
public async Task<int> Execute() { using (var reader = new StreamReader(FileName, Encode)) { XmlReader xmlReader = new XmlTextReader(reader); xmlReader.ReadStartElement(); while (xmlReader.Read()) { var xdoc = new XmlDocument(); string content = xmlReader.ReadOuterXml(); if (string.IsNullOrEmpty(content)) { break; } xdoc.LoadXml(content); for (int i = 0; i < xdoc.DocumentElement.ChildNodes.Count; i++) { var xele = xdoc.DocumentElement.ChildNodes[i] as XmlElement; if (i != 0) { _logger.InfoLine(","); } _logger.InfoLine(xele.InnerText); } _logger.InfoLine(""); } xmlReader.Close(); return 0; } }
public string ConstructBody() { using (var reader = new XmlTextReader(new StringReader(page))) { reader.DtdProcessing = DtdProcessing.Ignore; reader.ReadToFollowing("body"); return reader.ReadOuterXml(); } }
public bool parseXMLAsDelimited(string sSource, string sDest, string record_node, T_Fields[] arr_args, string filing_file = null, bool bSort = false) { System.Collections.ArrayList filing_values = null; string tmpDest = System.IO.Path.GetTempFileName(); System.IO.FileStream xmlStream = new System.IO.FileStream(sSource, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.StreamWriter writer = new System.IO.StreamWriter(tmpDest, false, new System.Text.UTF8Encoding(false)); System.Xml.XmlReader rd = new System.Xml.XmlTextReader(xmlStream, System.Xml.XmlNodeType.Document, null); string sreturn = ""; try { while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.LocalName == record_node || rd.Name == record_node) { sreturn = rd.ReadOuterXml(); writer.WriteLine(parseNode(sreturn)); } } } if (rd != null) { rd.Close(); } if (writer != null) { writer.Close(); } return(processFile2MARC(tmpDest, sDest, arr_args, filing_file, bSort)); } catch (System.Exception pp) { LastError = "Unable to process XML File.\n\nFull Exception:\n" + pp.ToString(); if (rd != null) { rd.Close(); } if (writer != null) { writer.Close(); } return(false); } }
public XmlDocument ConvertToXMLDoc(string xmlData) { XmlDocument xmlDoc = new XmlDocument(); System.Xml.XmlTextReader xmlReader; xmlReader = new System.Xml.XmlTextReader(xmlData, System.Xml.XmlNodeType.Document, null); xmlReader.ReadOuterXml(); xmlDoc.Load(xmlReader); return xmlDoc; }
private static string RequestRestaurantInfo(string strURL) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream s = response.GetResponseStream(); XmlTextReader reader = new XmlTextReader(s); reader.MoveToContent(); string xml = reader.ReadOuterXml(); return xml; }
public void CreateLookup(SPFeatureReceiverProperties properties, SPWeb web, String filePath) { string fieldId; bool isReading = true; XmlDocument document = GetXmlDocument(properties.Definition, filePath, web.Locale); using (XmlTextReader reader = new XmlTextReader(new StringReader(document.OuterXml))) { CreateListMapping(properties); while (true) { if (reader.LocalName != "Field" || isReading) { if (!reader.Read()) { break; } } if (reader.LocalName == "Field") { if (reader.MoveToAttribute("Type") && reader.Value == "Lookup" && reader.MoveToAttribute("Name")) { fieldId = reader.Value; if (lookupsListMapping.ContainsKey(fieldId)) { String listName = lookupsListMapping[fieldId]; SPList list = GetListForLookup(listName, web); reader.MoveToContent(); XmlDocument doc = new XmlDocument(); String fieldElement = reader.ReadOuterXml(); doc.LoadXml(fieldElement); XPathNavigator navigator = doc.DocumentElement.CreateNavigator(); navigator.CreateAttribute("", "List", "", list.ID.ToString()); SPFieldLookup field = (SPFieldLookup)web.Fields[fieldId]; AddWebIdAttribute(web, doc); field.SchemaXml = RemoveXmlnsAttribute(doc.OuterXml); field.Update(true); isReading = false; continue; } } } isReading = true; } } }
public void makeJob() { if (languages.Count == 0) { scanLanguages(); } using (reader = new XmlTextReader(path)) { while (reader.Read()) { if (reader.IsStartElement() && reader.LocalName == "tu") { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(reader.ReadOuterXml()); foreach (XmlNode item in xmlDoc.FirstChild.ChildNodes) { if (item.LocalName == "tuv") { string lang; if (null == item.Attributes["xml:lang"]) { lang = item.Attributes["lang"].Value; } else { lang = item.Attributes["xml:lang"].Value; } int columnNumber = languages[lang]; foreach (XmlNode seg in item.ChildNodes) { if (seg.LocalName == "seg") { foreach (XmlNode txt in seg.ChildNodes) { if (txt.NodeType == XmlNodeType.Text) { output.addCell(columnNumber, txt.Value); } } } } } } output.writeRow(); } } } output.Close(); }
/// <summary> /// Loads the nodes from Xml /// </summary> public void LoadXml(string vsFileName) { XmlTextReader reader = new XmlTextReader(vsFileName); while (reader.Read()) { switch (reader.Name) { case "RuleBase": if (reader.NodeType != XmlNodeType.EndElement) { CreateRulesBase(reader); } break; case "ContinuousRuleVariable": CreateContinuousRuleVariable(reader.ReadOuterXml()); break; case "Rule": //reader.ReadOuterXml(); CreateRules(reader.ReadOuterXml()); break; } } reader.Close(); }
public void LoadSingleElement(string filename, XmlTextReader sourceReader) { _filename = filename; _lineOffset = sourceReader.LineNumber; string outerXml = sourceReader.ReadOuterXml(); try { _reader = new XmlTextReader(new StringReader(outerXml), sourceReader.NameTable); base.Load(_reader); } finally { if (_reader != null) { _reader.Close(); _reader = null; } } }
public List<Product> GetProductList() { List<Product> list = new List<Product>(); XmlTextReader reader = new XmlTextReader(dataFileName); reader.MoveToContent(); XmlDocument doc = new XmlDocument(); doc.LoadXml(reader.ReadOuterXml()); XmlNodeList nodes = doc.SelectNodes("products/product"); foreach (XmlNode node in nodes) { Product product = new Product(node.Attributes["id"].Value, node.Attributes["name"].Value, Convert.ToDouble(node.Attributes["price"].Value)); list.Add(product); } reader.Close(); return list; }
/// <summary> /// Construct the Belief Node given the input Xml /// </summary> /// <param name="vsXml">Xml Data</param> public BeliefNode(string vsXml) { XmlTextReader reader = new XmlTextReader(new StringReader(vsXml)); reader.Read(); Name = reader.GetAttribute("name"); PriorProbability = float.Parse(reader.GetAttribute("priorprob")); CurrentProbability = float.Parse(reader.GetAttribute("currentprob")); while(reader.Read()) { switch (reader.Name) { case "Arcs" : moArcs = new Arcs(reader.ReadOuterXml()); break; } } }
internal string ReadXmlFile(string location) { TTE.Log(location); string xml; Match testHttp = Regex.Match(location, "^(http|https)://"); if (testHttp.Success) { XmlTextReader oTR = new XmlTextReader(location); xml = oTR.ReadOuterXml(); } else { StreamReader oSR = new StreamReader(location); xml = oSR.ReadToEnd(); oSR.Close(); oSR.Dispose(); GC.Collect(); } return xml; }
public void ProcessPages() { XmlTextReader reader = new XmlTextReader(this.InputStream); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "page") { PageProcessor.ProcessPage(reader.ReadOuterXml()); } break; default: // Do nothing for now break; } } }
public Product GetProductByID(string anID) { Product product = null; XmlTextReader reader = new XmlTextReader(dataFileName); reader.MoveToContent(); XmlDocument doc = new XmlDocument(); doc.LoadXml(reader.ReadOuterXml()); XmlNode productNode = doc.SelectSingleNode("products/product[@id=" + anID + "]"); if (productNode != null) { product = new Product(productNode.Attributes["id"].Value, productNode.Attributes["name"].Value, Convert.ToDouble(productNode.Attributes["price"].Value)); } reader.Close(); return product; }
/// <summary> /// Gets a data set object from an XML data set formatted as a String. /// </summary> /// <param name="xmlData">XML data string in standard DataSet format.</param> /// <returns>A <see cref="DataSet"/> object.</returns> public static DataSet GetDataSet(this string xmlData) { DataSet dataSet = new DataSet(); XmlTextReader xmlReader = new XmlTextReader(xmlData, XmlNodeType.Document, null); xmlReader.ReadOuterXml(); // Reads the outer XML into the Dataset. dataSet.ReadXml(xmlReader); return dataSet; }
private void ReadFeedHeader () { if (IsUpToDate (feed_file)) { is_valid_file = false; return; } try { Log.Debug ("Opening feed file: {0}", feed_file); reader = new XmlTextReader (feed_file); reader.WhitespaceHandling = WhitespaceHandling.None; is_valid_file = true; // move to beginning of document reader.MoveToContent(); // move to <rss ...> node reader.ReadStartElement ("rss"); // move to <channel> node reader.ReadStartElement ("channel"); // read <title> do { string elementName = reader.Name; if (elementName == "item") break; switch (elementName) { case "title": reader.ReadStartElement ("title"); channel_title = reader.ReadString (); reader.ReadEndElement (); break; case "link": reader.ReadStartElement ("link"); channel_link = reader.ReadString (); reader.ReadEndElement (); break; case "description": reader.ReadStartElement ("description"); channel_description = reader.ReadString (); reader.ReadEndElement (); break; // ignore other elements default: reader.ReadOuterXml (); break; } } while (!reader.EOF && reader.NodeType == XmlNodeType.Element); } catch (XmlException ex) { Log.Warn (ex, "Caught exception parsing feed file:"); is_valid_file = false; reader.Close (); } }
public void LoadSingleElement (string filename, XmlTextReader sourceReader) { fileName = filename; lineNumber = sourceReader.LineNumber; string xml = sourceReader.ReadOuterXml(); reader = new XmlTextReader (new StringReader (xml), sourceReader.NameTable); Load (reader); reader.Close (); }
// Read the current node, including all markup. public override String ReadOuterXml() { return(reader.ReadOuterXml()); }
bool ModifyOtherDbRecords = false; // 同步过程是否修改指定的同步读者库以外的其它读者库中的(和卡中心记录中id匹配的那些)记录 // 从XML文件中读取全部记录,同步到读者库中 // parameters: // strLastNumber 本次处理的起点号码。如果为空,表示全部处理 // ids [out]顺便输出已经处理的id字符串数组 // return: // -1 error // 0 succeed // 1 中断 int WriteToReaderDb( string strInputFileName, string strLastNumber, out string strMaxNumber, out List<string> ids, out string strError) { strError = ""; strMaxNumber = ""; ids = new List<string>(); int nRet = 0; int nCreateCount = 0; // 新创建的记录数 int nChangedCount = 0; // 修改的记录数 int nNotChangedCount = 0; // 没有修改的记录数 Debug.Assert(string.IsNullOrEmpty(this.IdElementName) == false, ""); Debug.Assert(string.IsNullOrEmpty(this.From) == false, ""); Debug.Assert(string.IsNullOrEmpty(this.PatronDbName) == false, ""); SessionInfo sessioninfo = GetTempSessionInfo(); if (string.IsNullOrEmpty(strLastNumber) == true) strLastNumber = "-1"; Int64 nStart = 0; if (Int64.TryParse(strLastNumber, out nStart) == false) { strError = "参数strLastNumber值 '" + strLastNumber + "' 错误,应当为纯数字"; return -1; } RmsChannel channel = this.RmsChannels.GetChannel(this.App.WsUrl); if (channel == null) { strError = "get channel error"; return -1; } Stream file = null; try { file = File.Open(strInputFileName, FileMode.Open, FileAccess.Read); } catch (Exception ex) { strError = "打开文件 " + strInputFileName + " 失败: " + ex.Message; return -1; } XmlTextReader reader = new XmlTextReader(file); try { bool bRet = false; while (true) { bRet = reader.Read(); if (bRet == false) { strError = "没有根元素"; return -1; } if (reader.NodeType == XmlNodeType.Element) break; } for (int i = 0; ; i++) { Thread.Sleep(1); // 避免处理太繁忙 #if NO // 2012/2/4 // 系统挂起的时候,不运行本线程 if (this.App.HangupReason == HangupReason.LogRecover) { strError = "因为系统挂起或暂停批处理而中断处理"; return -1; } #endif if (this.Stopped == true) { strError = "中断处理"; return -1; } if (this.Stopped == true) { return 1; } while (true) { bRet = reader.Read(); if (bRet == false) return 0; if (reader.NodeType == XmlNodeType.Element) break; } if (bRet == false) return 0; // 结束 string strSourceXml = reader.ReadOuterXml(); XmlDocument source_dom = new XmlDocument(); try { source_dom.LoadXml(strSourceXml); } catch (Exception ex) { strError = "strSourceXml字符串装入XMLDOM时出错: " + ex.Message; return -1; } string strID = DomUtil.GetElementText(source_dom.DocumentElement, this.IdElementName); if (string.IsNullOrEmpty(strID) == true) { strError = "来自卡中心的XML记录 '" + strSourceXml + "' 中没有名为 " + this.IdElementName + " 的元素,或其值为空"; return -1; } ids.Add(strID); // 进入范围才处理 if (i <= nStart) { continue; } int nRedoCount = 0; REDO: string strExistingXml = ""; string strOutputPath = ""; byte[] baTimestamp = null; // 检索所有读者库,看这条记录是否已经存在 // 通过特定检索途径获得读者记录 // return: // -1 error // 0 not found // 1 命中1条 // >1 命中多于1条 nRet = this.App.GetReaderRecXmlByFrom( // this.RmsChannels, channel, null, // this.PatronDbName, strID, this.From, out strExistingXml, out strOutputPath, out baTimestamp, out strError); if (nRet == -1) { strError = "获取读者记录 '" + strID + "' (检索途径 '" + this.From + "') 时发生错误: " + strError; return -1; } if (nRet > 1) { // 警告,检索命中不唯一 string strErrorText = "获取读者记录 '" + strID + "' (检索途径 '" + this.From + "') 时发现命中多条("+nRet.ToString()+")记录,这是一个严重错误,请系统管理员尽快检查修复"; this.AppendResultText(strErrorText + "\r\n"); this.App.WriteErrorLog(strErrorText); continue; } if (nRet == 0) { string strNewXml = ""; // 没有命中。需要创建新的读者记录 nRet = BuildNewPatronXml( source_dom, out strNewXml, out strError); if (nRet == -1) return -1; string strSavedXml = ""; string strSavedRecPath = ""; byte[] baNewTimestamp = null; DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue kernel_errorcode = DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue.NoError; LibraryServerResult result = this.App.SetReaderInfo( sessioninfo, "new", this.PatronDbName + "/?", strNewXml, null, null, out strExistingXml, out strSavedXml, out strSavedRecPath, out baNewTimestamp, out kernel_errorcode); if (result.Value == -1) { strError = "在数据库 " + this.PatronDbName + " 中创建读者记录时出错: " + result.ErrorInfo; return -1; } // this.AppendResultText("创建读者记录 " + strSavedRecPath + "\r\n"); this.SetProgressText("创建读者记录 " + strSavedRecPath); nCreateCount++; } else { // 观察是否在同步的读者库中 string strDbName = ResPath.GetDbName(strOutputPath); if (strDbName != this.PatronDbName && this.ModifyOtherDbRecords == false) { nNotChangedCount++; continue; } // 命中,需要检查和修改读者记录 XmlDocument exist_dom = new XmlDocument(); try { exist_dom.LoadXml(strExistingXml); } catch (Exception ex) { strError = "strExistingXml字符串装入XMLDOM时出错: " + ex.Message; return -1; } string strMergedXml = ""; // 检查记录有无修改 // return: // -1 出错 // 0 没有修改 // 1 有修改 nRet = MergePatronXml( exist_dom, source_dom, out strMergedXml, out strError); if (nRet == -1) return -1; if (nRet == 1) { string strSavedXml = ""; string strSavedRecPath = ""; byte[] baNewTimestamp = null; DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue kernel_errorcode = DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue.NoError; LibraryServerResult result = this.App.SetReaderInfo( sessioninfo, "change", strOutputPath, strMergedXml, strExistingXml, baTimestamp, out strExistingXml, out strSavedXml, out strSavedRecPath, out baNewTimestamp, out kernel_errorcode); if (result.Value == -1) { // 时间戳不匹配,重试 if (nRedoCount < 10 && kernel_errorcode == rms.Client.rmsws_localhost.ErrorCodeValue.TimestampMismatch) { nRedoCount++; goto REDO; } strError = "修改保存读者记录 '" + strOutputPath + "' 时出错: " + result.ErrorInfo; return -1; } // this.AppendResultText("更新读者记录 " + strSavedRecPath + "\r\n"); this.SetProgressText("更新读者记录 " + strSavedRecPath); nChangedCount++; } else { nNotChangedCount++; } } strMaxNumber = i.ToString(); } } finally { if (file != null) file.Close(); this.SetProgressText(""); this.AppendResultText("创建记录数 " + nCreateCount.ToString() + "; 修改记录数 " + nChangedCount.ToString() + "; 没有发生变化的记录数 " + nNotChangedCount.ToString() + "\r\n"); } return 0; }
static PrimitiveBaseShape ReadShape(XmlTextReader reader, string name) { PrimitiveBaseShape shape = new PrimitiveBaseShape(); if (reader.IsEmptyElement) { reader.Read(); return shape; } reader.ReadStartElement(name, String.Empty); // Shape string nodeName = string.Empty; while (reader.NodeType != XmlNodeType.EndElement) { nodeName = reader.Name; //m_log.DebugFormat("[XXX] Processing: {0}", reader.Name); ShapeXmlProcessor p = null; if (m_ShapeXmlProcessors.TryGetValue(reader.Name, out p)) { try { p(shape, reader); } catch (Exception e) { m_log.DebugFormat("[SceneObjectSerializer]: exception while parsing Shape {0}: {1}", nodeName, e); if (reader.NodeType == XmlNodeType.EndElement) reader.Read(); } } else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element in Shape {0}", reader.Name); reader.ReadOuterXml(); } } reader.ReadEndElement(); // Shape return shape; }
void StorePending (string name, XmlTextReader reader) { if (pending == null) pending = new Hashtable (); pending [name] = reader.ReadOuterXml (); }
public static SceneObjectPart Xml2ToSOP(XmlTextReader reader, IRegistryCore scene) { SceneObjectPart obj = new SceneObjectPart(scene); reader.ReadStartElement("SceneObjectPart"); string nodeName = string.Empty; while (reader.Name != "SceneObjectPart") { nodeName = reader.Name; SOPXmlProcessor p = null; if (m_SOPXmlProcessors.TryGetValue(reader.Name, out p)) { //m_log.DebugFormat("[XXX] Processing: {0}", reader.Name); try { p(obj, reader); } catch (Exception e) { m_log.DebugFormat("[SceneObjectSerializer]: exception while parsing {0}: {1}", nodeName, e); if (reader.NodeType == XmlNodeType.EndElement) reader.Read(); } } else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element {0}", nodeName); reader.ReadOuterXml(); // ignore } } reader.ReadEndElement(); // SceneObjectPart //m_log.DebugFormat("[XXX]: parsed SOP {0} - {1}", obj.Name, obj.UUID); return obj; }
static TaskInventoryDictionary ReadTaskInventory(XmlTextReader reader, string name) { TaskInventoryDictionary tinv = new TaskInventoryDictionary(); reader.ReadStartElement(name, String.Empty); if (reader.IsEmptyElement) { reader.Read(); return tinv; } while (reader.Name == "TaskInventoryItem") { reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory TaskInventoryItem item = new TaskInventoryItem(); while (reader.NodeType != XmlNodeType.EndElement) { TaskInventoryXmlProcessor p = null; if (m_TaskInventoryXmlProcessors.TryGetValue(reader.Name, out p)) p(item, reader); else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element in TaskInventory {0}, {1}", reader.Name, reader.Value); reader.ReadOuterXml(); } } reader.ReadEndElement(); // TaskInventoryItem tinv.Add(item.ItemID, item); } if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement(); // TaskInventory return tinv; }
private void GetRssFeeds(object state) { OutlineInfo outline = null; try { outline = (OutlineInfo)state; string xmlString = string.Empty; using (Stream rssStream = DownloadManager.GetFeed(outline.Outline.XmlUrl)) { using (XmlTextReader reader = new XmlTextReader(rssStream)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { xmlString = reader.ReadOuterXml(); break; } } } } ////convert to rss xmlString = RssXmlHelper.ConvertToRssXml(xmlString); if (!string.IsNullOrEmpty(xmlString)) { RssXmlSchemaValidator validator = new RssXmlSchemaValidator(); Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(Constants.Rss20Xsd)) { lock (aggregateRss) { validator.ValidXmlDoc(xmlString, new XmlTextReader(stream)); if (validator.IsValidXml) { aggregateRss.Add(xmlString); } } if (!validator.IsValidXml) { NotifySubscribers(null, "Rss not valid in OPML for - " + outline.Outline.XmlUrl, RssSeverityType.Warning); } } } } catch (Exception ex) { NotifySubscribers(ex, ex.Message, RssSeverityType.Error); } finally { rssEvents[outline.Index].Set(); } }
public static bool TryFromXml(string xml, out CoalescedSceneObjects coa) { // m_log.DebugFormat("[COALESCED SCENE OBJECTS SERIALIZER]: TryFromXml() deserializing {0}", xml); coa = null; using (StringReader sr = new StringReader(xml)) { using (XmlTextReader reader = new XmlTextReader(sr)) { try { reader.Read(); if (reader.Name != "CoalescedObject") { // m_log.DebugFormat( // "[COALESCED SCENE OBJECTS SERIALIZER]: TryFromXml() root element was {0} so returning false", // reader.Name); return false; } coa = new CoalescedSceneObjects(UUID.Zero); reader.Read(); while (reader.NodeType != XmlNodeType.EndElement && reader.Name != "CoalescedObject") { if (reader.Name == "SceneObjectGroup") { string soXml = reader.ReadOuterXml(); coa.Add(SceneObjectSerializer.FromOriginalXmlFormat(soXml)); } } reader.ReadEndElement(); // CoalescedObject } catch (Exception e) { m_log.ErrorFormat( "[COALESCED SCENE OBJECTS SERIALIZER]: Deserialization of xml failed with {0} {1}", e.Message, e.StackTrace); return false; } } } return true; }
// 将更新卡户信息完整表(AccountsCompleteInfo_yyyymmdd.xml)写入读者库 // return: // -1 error // 0 succeed // 1 中断 int WriteToReaderDb(string strLocalFilePath, out string strError) { strError = ""; int nRet = 0; XmlNode node = this.App.LibraryCfgDom.DocumentElement.SelectSingleNode("//zhengyuan/replication"); if (node == null) { strError = "尚未配置<zhangyuan><replication>参数"; return -1; } string strMapDbName = DomUtil.GetAttr(node, "mapDbName"); if (String.IsNullOrEmpty(strMapDbName) == true) { strError = "尚未配置<zhangyuan/replication>元素的mapDbName属性"; return -1; } Stream file = File.Open(strLocalFilePath, FileMode.Open, FileAccess.Read); if (file.Length == 0) return 0; try { XmlTextReader reader = new XmlTextReader(file); bool bRet = false; // 临时的SessionInfo对象 SessionInfo sessioninfo = new SessionInfo(this.App); // 模拟一个账户 Account account = new Account(); account.LoginName = "replication"; account.Password = ""; account.Rights = "setreaderinfo"; account.Type = ""; account.Barcode = ""; account.Name = "replication"; account.UserID = "replication"; account.RmsUserName = this.App.ManagerUserName; account.RmsPassword = this.App.ManagerPassword; sessioninfo.Account = account; // 找到根 while (true) { try { bRet = reader.Read(); } catch (Exception ex) { strError = "读XML文件发生错误: " + ex.Message; return -1; } if (bRet == false) { strError = "没有根元素"; return -1; } if (reader.NodeType == XmlNodeType.Element) break; } for (int i = 0; ; i++) { if (this.Stopped == true) return 1; bool bEnd = false; // 第二级元素 while (true) { bRet = reader.Read(); if (bRet == false) { bEnd = true; // 结束 break; } if (reader.NodeType == XmlNodeType.Element) break; } if (bEnd == true) break; this.AppendResultText("处理 " + (i + 1).ToString() + "\r\n"); // 记录体 string strXml = reader.ReadOuterXml(); // return: // -1 error // 0 已经写入 // 1 没有必要写入 nRet = WriteOneReaderInfo( sessioninfo, strMapDbName, strXml, out strError); if (nRet == -1) return -1; } return 0; } finally { file.Close(); } }
/// <summary> /// Set the parameters used to validate licenses created by this provider. /// </summary> /// <remarks> /// This must be called by the client software prior to obtaining licenses using the EncryptedLicenseProvider. /// The parameters are generated using the Infralution License Key Generator and pasted into the calling client code. /// </remarks> /// <param name="licenseParameters">An XML string containing parameters used to validate licenses</param> public static void SetParameters(string licenseParameters) { // parse the validation parameters // XmlReader reader = new XmlTextReader(licenseParameters, XmlNodeType.Element, null); while (reader.Read()) { if (reader.IsStartElement()) { if (reader.LocalName == "RSAKeyValue") { _rsaParameters = reader.ReadOuterXml(); } if (reader.LocalName == "DesignSignature") { string key = reader.ReadElementString(); _designSignature = Convert.FromBase64String(key); } if (reader.LocalName == "RuntimeSignature") { string key = reader.ReadElementString(); _runtimeSignature = Convert.FromBase64String(key); } } } reader.Close(); }
public string[] parseXMLAsDelimitedPreview(string sSource, string record_node, int iPreview = 3) { System.IO.FileStream xmlStream = new System.IO.FileStream(sSource, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.Xml.XmlReader rd = new System.Xml.XmlTextReader(xmlStream, System.Xml.XmlNodeType.Document, null); string sxml = ""; string sbody = ""; string sheader = ""; int iCount = 0; try { while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.LocalName == record_node || rd.Name == record_node) { sxml = rd.ReadOuterXml(); if (sheader.Length == 0) { sheader = parseNode(sxml, true); } if (iCount < iPreview) { sbody += parseNode(sxml) + "\n"; iCount++; } else { break; } } } } sbody = sbody.TrimEnd("\n".ToCharArray()); System.Collections.ArrayList tList = new System.Collections.ArrayList(); tList.Add(sheader); foreach (string s in sbody.Split("\n".ToCharArray())) { tList.Add(s); } if (rd != null) { rd.Close(); } string[] arr_return = new string[tList.Count]; tList.CopyTo(arr_return); return(arr_return); } catch (System.Exception pp) { LastError = "Unable to process XML File.\n\nFull Exception:\n" + pp.ToString(); if (rd != null) { rd.Close(); } return(null); } }
internal void ParseSCPD(String XML, int startLine) { bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { try { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { int embeddedLine = XMLDoc.LineNumber; //ParseActionXml("<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>", embeddedLine); ParseActionXml(XMLDoc.ReadOuterXml(), embeddedLine-1); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc, startLine); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While } catch (XMLParsingException ex) { throw ex; } catch (Exception ex) { throw new XMLParsingException("Invalid SCPD XML", startLine + XMLDoc.LineNumber, XMLDoc.LinePosition, ex); } // Add Associations foreach (UPnPAction A in this.Actions) { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } } // End of If }
public void IXmlLineInfo () { // See bug #63507 XmlTextReader aux = new XmlTextReader ( new StringReader ("<all><hello></hello><bug></bug></all>")); AssertEquals (0, aux.LineNumber); AssertEquals (0, aux.LinePosition); aux.MoveToContent(); AssertEquals (1, aux.LineNumber); AssertEquals (2, aux.LinePosition); aux.Read(); AssertEquals (1, aux.LineNumber); AssertEquals (7, aux.LinePosition); aux.ReadOuterXml(); AssertEquals (1, aux.LineNumber); AssertEquals (22, aux.LinePosition); aux.ReadInnerXml(); AssertEquals (1, aux.LineNumber); AssertEquals (34, aux.LinePosition); aux.Read(); AssertEquals (1, aux.LineNumber); AssertEquals (38, aux.LinePosition); aux.Close(); AssertEquals (0, aux.LineNumber); AssertEquals (0, aux.LinePosition); }