public static void Read(XmlDocument xml) { List<DecModel> list = new List<DecModel>(); XNamespace ns = "HTTP://CLIS.HB_DEC"; using (var nodeReader = new XmlNodeReader(xml)) { nodeReader.MoveToContent(); XDocument xdoc= XDocument.Load(nodeReader); var seqNo = xdoc.Descendants(ns + "SEQ_NO").First().Value; var entryId = xdoc.Descendants(ns + "ENTRY_ID").First().Value; var ieFlag = xdoc.Descendants(ns + "I_E_FLAG").First().Value; foreach (var element in xdoc.Descendants(ns + "HB_DEC_LIST")) { Console.WriteLine(element.Element(ns + "COP_G_NO").Value, element.Element(ns + "QTY").Value); DecModel item = new DecModel(); item.EntryId = entryId; item.SeqNo = seqNo; item.IEFlag = ieFlag; item.GNo = element.Element(ns + "COP_G_NO").Value; item.Qty = Convert.ToDecimal(element.Element(ns + "QTY").Value); list.Add(item); } if (list.Count > 0) { SqlHelper.Insert(list); } } }
public List<WpPost> GetPosts(WpImportOptions options) { Item mediaInnerItem = _db.GetItem(_mediaItemId); if (mediaInnerItem == null) { Logger.Error(String.Format("Media item for import could not be found (id: {0}, db: {1})", _mediaItemId, _db.Name)); return new List<WpPost>(0); } MediaItem mediaItem = new MediaItem(mediaInnerItem); XmlDocument xmdDoc = new XmlDocument(); var mediaStream = MediaManager.GetMedia(mediaItem).GetStream(); if (mediaStream == null || mediaStream.MimeType != "text/xml") { Logger.Error(String.Format("MediaStream for imported item is null or uploaded file has is incorrect format (id: {0}, db: {1})", _mediaItemId, _db.Name)); return new List<WpPost>(0); } xmdDoc.Load(mediaStream.Stream); using (var nodeReader = new XmlNodeReader(xmdDoc)) { nodeReader.MoveToContent(); var xDocument = XDocument.Load(nodeReader); var posts = (from item in xDocument.Descendants("item") select new WpPost(item, options)).ToList(); return posts; } }
public static XDocument ToXDocument(this XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader); } }
public static void Read(XmlDocument xml) { List<DecModel> list = new List<DecModel>(); //XNamespace ns = "HTTP://CLIS.HB_DEC"; using (var nodeReader = new XmlNodeReader(xml)) { nodeReader.MoveToContent(); XDocument xdoc= XDocument.Load(nodeReader); var orderno = xdoc.Descendants("ERP_OBJECT_ID").First().Value; var preno = xdoc.Descendants("PRE_GATEPASS_NO").First().Value; var gatepassno = xdoc.Descendants("GATEPASS_NO").First().Value; if (orderno.Length > 0 && gatepassno.Length > 0) { SqlHelper.UpdateCLSStatus(orderno, gatepassno ); } } }
private string SerializeXmlNode(XmlNode node) { string json = JsonConvert.SerializeXmlNode(node, Formatting.Indented); XmlNodeReader reader = new XmlNodeReader(node); #if !NET20 XObject xNode; if (node is XmlDocument) { xNode = XDocument.Load(reader); } else if (node is XmlAttribute) { XmlAttribute attribute = (XmlAttribute) node; xNode = new XAttribute(XName.Get(attribute.LocalName, attribute.NamespaceURI), attribute.Value); } else { reader.MoveToContent(); xNode = XNode.ReadFrom(reader); } string linqJson = JsonConvert.SerializeXNode(xNode, Formatting.Indented); Assert.AreEqual(json, linqJson); #endif return json; }
public static XDocument ToXDocument(this XmlDocument xmlDocument, LoadOptions options = LoadOptions.None) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader, options); } }
/// <summary> /// Converts a <see cref="XmlDocument"/> instance into a <see cref="XDocument"/> instance. /// </summary> /// <param name="input">The <see cref="XmlDocument"/> instance to convert.</param> /// <returnsAn <see cref="XDocument"/> instance containing the data from the input <see cref="XmlDocument"/>.</returns> public static XDocument ToXDocument(this XmlDocument input) { using (var xmlStream = new XmlNodeReader(input)) { xmlStream.MoveToContent(); return XDocument.Load(xmlStream); } }
/// <summary> /// Converts an <see cref="System.Xml.XmlNode"/> to a <see cref="System.Xml.Linq.XElement"/> /// </summary> /// <param name="node">Node to convert</param> /// <returns>Converted node</returns> public static XElement ToXElement(this XmlNode node) { using (var x = new XmlNodeReader(node)) { x.MoveToContent(); return XElement.Load(x); } }
public static XElement ToXDocument(this XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); var xDoc = XDocument.Load(nodeReader); return XElement.Parse(xDoc.ToString()); } }
internal static string ReadTextElementAsTrimmedString(XmlElement element) { if (element == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element"); } XmlReader reader = new XmlNodeReader(element); reader.MoveToContent(); return XmlUtil.Trim(reader.ReadElementContentAsString()); }
public virtual NvdlValidatorGenerator CreateGenerator (NvdlValidate validate, string schemaType, NvdlConfig config) { this.validate = validate; this.schema_type = schemaType; this.config = config; XmlReader schema = null; // FIXME: we need a bit more strict check. if (schemaType.Length < 5 || !schemaType.EndsWith ("xml") || Char.IsLetter (schemaType, schemaType.Length - 4)) return null; string schemaUri = validate.SchemaUri; XmlElement schemaBody = validate.SchemaBody; if (schemaUri != null) { if (schemaBody != null) throw new NvdlCompileException ("Both 'schema' attribute and 'schema' element are specified in a 'validate' element.", validate); schema = GetSchemaXmlStream (schemaUri, config, validate); } else if (validate.SchemaBody != null) { XmlReader r = new XmlNodeReader (schemaBody); r.MoveToContent (); r.Read (); // Skip "schema" element r.MoveToContent (); if (r.NodeType == XmlNodeType.Element) schema = r; else schema = GetSchemaXmlStream (r.ReadString (), config, validate); } if (schema == null) return null; return CreateGenerator (schema, config); }
static void Main(string[] args) { var artists = new List<string>(); var albums = new List<string>(); var catalogFilePath = "../../../../catalog.xml"; XmlDocument doc = new XmlDocument(); doc.Load(catalogFilePath); using (XmlNodeReader reader = new XmlNodeReader(doc)) { reader.MoveToContent(); reader.ReadToDescendant("album"); while (reader.Read()) { var albumName = reader.ReadInnerXml(); albums.Add(albumName); var artist = reader.ReadInnerXml(); artists.Add(artist); reader.ReadToFollowing("album"); } } string albumFilePath = "../../album.xml"; Encoding encoding = Encoding.GetEncoding("windows-1251"); using (XmlTextWriter writer = new XmlTextWriter(albumFilePath, encoding)) { writer.Formatting = Formatting.Indented; writer.IndentChar = '\t'; writer.Indentation = 1; writer.WriteStartDocument(); writer.WriteStartElement("albums"); for (int i = 0, len = artists.Count; i < len; i++) { WriteAlbum(writer, albums[i], artists[i]); } writer.WriteEndDocument(); } Console.WriteLine("Document {0} created.", albumFilePath); }
private void btnConvert_Click(object sender, EventArgs e) { try { XmlDocument doc = new XmlDocument(); doc.Load(txtFileName.Text); XElement result = null; using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) { // the reader must be in the Interactive state in order to // Create a LINQ to XML tree from it. nodeReader.MoveToContent(); XElement xRoot = XElement.Load(nodeReader); result = DeployConverter.DeployConverter.ToUDSDeployElement(xRoot); } if (result != null) { SaveFileDialog sfd = new SaveFileDialog(); sfd.DefaultExt = "csml"; string sourcepath = txtFileName.Text; FileInfo file = new FileInfo(sourcepath); sfd.InitialDirectory = file.DirectoryName; sfd.FileName = Path.Combine(file.DirectoryName, "new.csml"); DialogResult dr = sfd.ShowDialog(); if (dr == System.Windows.Forms.DialogResult.OK) { XmlDocument d = new XmlDocument(); d.LoadXml(result.ToString()); d.Save(sfd.FileName); MessageBox.Show("轉換完成", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } } } catch (Exception ex) { MessageBox.Show("轉換過程中發生錯誤 : \n" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void DownloadBucket(string url, string targetPath, int parallelDownloads = 32) { Dictionary<string, string> etags; var di = new DirectoryInfo(targetPath); using (var s = di.GetFile("bucket.bson").Open(FileMode.OpenOrCreate)) { using (var br = new BsonReader(s)) { var se = new JsonSerializer(); etags = se.Deserialize<Dictionary<string, string>>(br) ?? new Dictionary<string, string>(); } } XDocument doc; XNamespace xmlns = "http://s3.amazonaws.com/doc/2006-03-01/"; Console.Write("Loading S3 bucket... "); while (true) { var xdoc = new XmlDocument(); xdoc.Load(url); var xnr = new XmlNodeReader(xdoc); xnr.MoveToContent(); doc = XDocument.Load(xnr); Console.WriteLine("found {0} items", doc.Descendants(xmlns + "Contents").Count()); if (!doc.Descendants(xmlns + "Contents").Any()) { continue; } break; } var actionsCompleted = 0; var actions = new List<Tuple<string, string>>(); Action<Tuple<string, string>> downloadingAction = t => { var etag = t.Item1; var path = t.Item2; var rpath = path.Replace('/', Path.DirectorySeparatorChar); var fi = new FileInfo(Path.Combine(di.FullName + Path.DirectorySeparatorChar, rpath)); if (fi.Directory != null && !fi.Directory.Exists) fi.Directory.Create(); else if (fi.Exists) fi.Delete(); var b = new UriBuilder(url); b.Path = b.Path.TrimEnd('/') + "/" + path; while (true) { try { File.Move(Http.Download(b.Uri.ToString()), fi.FullName); } catch { continue; } break; } lock (etags) { etags[path] = etag; actionsCompleted++; Console.Write("Downloading... ({0}/{1}, {2}%)\r", actionsCompleted, actions.Count, Math.Round(100 * (float)actionsCompleted / actions.Count, 0)); } }; foreach (var content in doc.Descendants(xmlns + "Contents")) { var xkey = content.Element(xmlns + "Key"); var xetag = content.Element(xmlns + "ETag"); if (xkey == null || xetag == null) continue; // Key as relative path var relpath = xkey.Value; // Compare etags var etag = xetag.Value.Trim('"'); if (!etags.ContainsKey(relpath)) etags.Add(relpath, null); if (etags[relpath] == etag) continue; // File or directory not changed // Local path var rellpath = relpath.Replace('/', Path.DirectorySeparatorChar); // Check if directory if (relpath.EndsWith("/")) // is a directory Directory.CreateDirectory(Path.Combine(di.FullName + Path.DirectorySeparatorChar, rellpath)); else { actions.Add(new Tuple<string, string>(etag, relpath)); } } Console.WriteLine("Starting download of {0} items.", actions.Count); Parallel.ForEach(actions, new ParallelOptions { MaxDegreeOfParallelism = 16 }, downloadingAction); while (actionsCompleted < actions.Count) Thread.Sleep(25); Console.WriteLine("Download of {0} items from Amazon S3 bucket finished!", actions.Count); actions.Clear(); using (var s = di.GetFile("bucket.bson").Open(FileMode.OpenOrCreate)) { using (var bw = new BsonWriter(s)) { var se = new JsonSerializer(); se.Serialize(bw, etags); } } }
private XDocument XmlDocumentToXDocument(XmlDocument xml) { using (var nodeReader = new XmlNodeReader(xml)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader); } }
void DoDeserializeSection (XmlReader reader) { reader.MoveToContent (); string protection_provider = null; string config_source = null; string localName; while (reader.MoveToNextAttribute ()) { localName = reader.LocalName; if (localName == "configProtectionProvider") protection_provider = reader.Value; else if (localName == "configSource") config_source = reader.Value; } /* XXX this stuff shouldn't be here */ { if (protection_provider != null) { ProtectedConfigurationProvider prov = ProtectedConfiguration.GetProvider (protection_provider, true); XmlDocument doc = new ConfigurationXmlDocument (); reader.MoveToElement (); doc.Load (new StringReader (reader.ReadInnerXml ())); XmlNode n = prov.Decrypt (doc); reader = new XmlNodeReader (n); SectionInformation.ProtectSection (protection_provider); reader.MoveToContent (); } } if (config_source != null) SectionInformation.ConfigSource = config_source; SectionInformation.SetRawXml (RawXml); if (SectionHandler == null) DeserializeElement (reader, false); }
public XmlReader CreateReader () { #if NET_2_1 var reader = XmlReader.Create (new StringReader (body)); #else var reader = new XmlNodeReader (body); #endif reader.MoveToContent (); return reader; }
/// <summary> /// Parses an IM log file and sends the information to GDS /// </summary> /// <param name="logFile">The IM conversations log file</param> /// <param name="lastIndexed">messages older than this will not be sent to GDS</param> private void ParseAndSendMessages(string logFile, DateTime lastIndexed) { XmlDocument doc = new XmlDocument(); doc.Load(logFile); XmlNodeReader reader = new XmlNodeReader(doc); // reset user and buddy name userName = null; buddyName = null; // Moves the reader to the root element. reader.MoveToContent(); // move to the first message reader.Read(); while(reader.LocalName == "Message") { // check the date of the message - if older skip reader.MoveToAttribute("DateTime"); DateTime messageDateTime = DateTime.Parse(reader.Value); reader.MoveToElement(); // if older than the last indexing time, skip the message if (messageDateTime.CompareTo(lastIndexed) <= 0) { reader.Skip(); continue; } // get message data MSNMessageData messageData = ParseMessageData(reader.ReadOuterXml()); // send this message to GDS for indexing SendMessageData(messageData); } }
private static SerializedInfo ParseXmlPacket(Session session, string content) { XmlDocument doc = new XmlDocument(); doc.LoadXml(content); using (var nodeReader = new XmlNodeReader(doc)) { nodeReader.MoveToContent(); XElement contentNode = XDocument.Load(nodeReader).Root; XElement clientInvokeNode = FetchClientInvokeNode(contentNode); string clientInvokeId = clientInvokeNode == null ? string.Empty : clientInvokeNode.Value; return SerializedInfo.CreateForXml(session, clientInvokeId, contentNode); } }
private static XDocument ToXDocument(XmlDocument xmlDocument) { using (XmlNodeReader nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent (); return XDocument.Load (nodeReader); } }
public string GetElementValue(XmlDocument xml, string tag) { if (xml == null) return null; XDocument xdoc = null; using (var reader = new XmlNodeReader(xml)) { reader.MoveToContent(); xdoc = XDocument.Load(reader); } XName xn = tag; if (!string.IsNullOrWhiteSpace(xdoc.Root.GetDefaultNamespace().NamespaceName)) xn = XName.Get(tag, xdoc.Root.GetDefaultNamespace().NamespaceName); if (xdoc.Root.Element(xn) != null) { return xdoc.Root.Element(xn).Value; } else return string.Empty; }
/// <summary> /// Full parse of the Package-specific Object tag /// </summary> /// <remarks>Side effect of updating _signingTime, _signingTimeFormat, /// _partManifest, _partEntryManifest and _relationshipManifest</remarks> /// <exception cref="XmlException">throws if markup does not match OPC spec</exception> private void ParsePackageDataObject() { if (!_dataObjectParsed) { EnsureXmlSignatureParsed(); // find the package-specific Object tag XmlNodeList nodeList = GetPackageDataObject().Data; // The legal parent is a "Package" Object tag with 2 children // <Manifest> and <SignatureProperties> if (nodeList.Count != 2) throw new XmlException(SR.Get(SRID.XmlSignatureParseError)); // get a NodeReader that allows us to easily and correctly skip comments XmlReader reader = new XmlNodeReader(nodeList[0].ParentNode); // parse the <Object> tag - ensure that it is in the correct namespace reader.Read(); // enter the Object tag if (String.CompareOrdinal(reader.NamespaceURI, SignedXml.XmlDsigNamespaceUrl) != 0) throw new XmlException(SR.Get(SRID.XmlSignatureParseError)); string signaturePropertiesTagName = XTable.Get(XTable.ID.SignaturePropertiesTagName); string manifestTagName = XTable.Get(XTable.ID.ManifestTagName); bool signaturePropertiesTagFound = false; bool manifestTagFound = false; while (reader.Read() && (reader.NodeType == XmlNodeType.Element)) { if (reader.MoveToContent() == XmlNodeType.Element && (String.CompareOrdinal(reader.NamespaceURI, SignedXml.XmlDsigNamespaceUrl) == 0) && reader.Depth == 1) { if (!signaturePropertiesTagFound && String.CompareOrdinal(reader.LocalName, signaturePropertiesTagName) == 0) { signaturePropertiesTagFound = true; // parse the <SignatureProperties> tag _signingTime = XmlSignatureProperties.ParseSigningTime( reader, _signedXml.Signature.Id, out _signingTimeFormat); continue; } else if (!manifestTagFound && String.CompareOrdinal(reader.LocalName, manifestTagName) == 0) { manifestTagFound = true; // parse the <Manifest> tag XmlSignatureManifest.ParseManifest(_manager, reader, out _partManifest, out _partEntryManifest, out _relationshipManifest); continue; } } throw new XmlException(SR.Get(SRID.XmlSignatureParseError)); } // these must both exist on exit if (!(signaturePropertiesTagFound && manifestTagFound)) throw new XmlException(SR.Get(SRID.XmlSignatureParseError)); _dataObjectParsed = true; } }
/// <summary> /// Removing this from the IXmlSerializable Implementation because engineers keep exposing the SerialzableDictionary object /// and that cannot be allowed because nobody else can deserialize. It is for persistance only so the logic was moved here. /// </summary> /// <param name="doc">The doc.</param> /// <returns></returns> private IList<string> convertFromXml(XmlDocument doc) { XmlReader reader = new XmlNodeReader(doc); //First check empty element and return if found bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return null; IList<string> result = new List<string>(); reader.ReadStartElement(DocumentElement); if (reader.NodeType != XmlNodeType.Element) return result; //Loop through the nodes representing this object in the reader while (reader.NodeType != XmlNodeType.EndElement) { //First try the optimized format //string key = reader.GetAttribute(KEY_ATTRIBUTE); string typeName = reader.GetAttribute(TYPE_ATTRIBUTE); //Read the Xml element representing a new key & value pair reader.ReadStartElement(ITEM_ELEMENT); //if (String.IsNullOrEmpty(key)) //{ // //Key is not being stoed as an attribute - this must be xml in the old format // //KEEP THIS CODE FOR BACKWARDS COMPATIBILITY // //First we need to get the type of the object written to the Xml during serialization so that // //we can create a new serializer that understands how to deserialize this type. // typeName = reader.GetAttribute(TYPE_ATTRIBUTE); // //Read the Xml element representing the key in this key & value pair // reader.ReadStartElement(KEY_ELEMENT); // //Allright now create the serializer and deserialize the defined object type // XmlSerializer keySerializer = new XmlSerializer(typeof(string)); // //key = (string)keySerializer.Deserialize(reader); // if (key == null) // throw new ApplicationException(String.Format("Null key encountered on line {0}", // reader.Depth)); // //Read the end of the key element // reader.ReadEndElement(); //} Type valuetype = (typeName != null ? Type.GetType(typeName) : typeof(object)) ?? typeof(object); //Read the Xml element representing the value in this key & value pair reader.ReadStartElement(VALUE_ELEMENT); //Now create the serialize and deserialize the object type defined from the type attribute XmlSerializer valueSerializer = new XmlSerializer(valuetype); //HACK!!! //Make sure you catch any errors caused by invalid types cannot be deserialized. For example this whole process //kept blowing up because the type ould not be serialized. string value;// = (TValue) valueSerializer.Deserialize(reader); try { value = (string)valueSerializer.Deserialize(reader); } catch (Exception) { value = default(string); //skip top the end of the current element reader.Skip(); } //Read the end of the value element reader.ReadEndElement(); //Now add the deserialized objects to the hashtable. result.Add(value); //Read the end of the element holding the key and value elements if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == ITEM_ELEMENT) reader.ReadEndElement(); reader.MoveToContent(); } //All done - read the ending element reader.ReadEndElement(); return result; }
/// <summary> /// Reads a <see cref="SecurityToken"/> from the provided XML representation. /// </summary> /// <param name="securityTokenXml">The XML representation of the security token.</param> /// <param name="securityTokenHandlers">The <see cref="SecurityTokenHandlerCollection"/> used to /// read the token.</param> /// <returns>A <see cref="SecurityToken"/>.</returns> protected virtual SecurityToken ReadSecurityToken(XmlElement securityTokenXml, SecurityTokenHandlerCollection securityTokenHandlers) { SecurityToken securityToken = null; XmlReader reader = new XmlNodeReader(securityTokenXml); reader.MoveToContent(); securityToken = securityTokenHandlers.ReadToken(reader); if (securityToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4051, securityTokenXml, reader.LocalName, reader.NamespaceURI))); } return securityToken; }
// LAMESPEC: XmlReadMode.Fragment is far from presisely // documented. MS.NET infers schema against this mode. public XmlReadMode ReadXml (XmlReader input, XmlReadMode mode) { switch (input.ReadState) { case ReadState.EndOfFile: case ReadState.Error: case ReadState.Closed: return mode; } // Skip XML declaration and prolog input.MoveToContent (); if (input.EOF) return mode; // FIXME: We need more decent code here, but for now // I don't know the precise MS.NET behavior, I just // delegate to specific read process. switch (mode) { case XmlReadMode.IgnoreSchema: return ReadXmlIgnoreSchema (input, mode, true); case XmlReadMode.ReadSchema: return ReadXmlReadSchema (input, mode, true); } // remaining modes are: Auto, InferSchema, Fragment, Diffgram XmlReader reader = input; int depth = reader.Depth; XmlReadMode result = mode; bool skippedTopLevelElement = false; string potentialDataSetName = null; XmlDocument doc = null; bool shouldReadData = mode != XmlReadMode.DiffGram; bool shouldNotInfer = Tables.Count > 0; switch (mode) { case XmlReadMode.Auto: case XmlReadMode.InferSchema: doc = new XmlDocument (); do { doc.AppendChild (doc.ReadNode (reader)); } while (!reader.EOF && doc.DocumentElement == null); reader = new XmlNodeReader (doc); reader.MoveToContent (); break; case XmlReadMode.DiffGram: if (!(reader.LocalName == "diffgram" && reader.NamespaceURI == XmlConstants.DiffgrNamespace)) goto case XmlReadMode.Auto; break; } switch (mode) { case XmlReadMode.Auto: case XmlReadMode.InferSchema: case XmlReadMode.ReadSchema: if (!(reader.LocalName == "diffgram" && reader.NamespaceURI == XmlConstants.DiffgrNamespace) && !(reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace)) potentialDataSetName = reader.LocalName; goto default; case XmlReadMode.Fragment: break; default: if (!(reader.LocalName == "diffgram" && reader.NamespaceURI == XmlConstants.DiffgrNamespace) && !(reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace)) { if (!reader.IsEmptyElement) { reader.Read (); reader.MoveToContent (); skippedTopLevelElement = true; } else { switch (mode) { case XmlReadMode.Auto: case XmlReadMode.InferSchema: DataSetName = reader.LocalName; break; } reader.Read (); } } break; } // If schema, then read the first element as schema if (reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace) { shouldNotInfer = true; switch (mode) { case XmlReadMode.IgnoreSchema: case XmlReadMode.InferSchema: reader.Skip (); break; case XmlReadMode.Fragment: ReadXmlSchema (reader); break; case XmlReadMode.DiffGram: case XmlReadMode.Auto: if (Tables.Count == 0) { ReadXmlSchema (reader); if (mode == XmlReadMode.Auto) result = XmlReadMode.ReadSchema; } else { // otherwise just ignore and return IgnoreSchema reader.Skip (); result = XmlReadMode.IgnoreSchema; } break; case XmlReadMode.ReadSchema: ReadXmlSchema (reader); break; } } // If diffgram, then read the first element as diffgram if (reader.LocalName == "diffgram" && reader.NamespaceURI == XmlConstants.DiffgrNamespace) { switch (mode) { case XmlReadMode.Auto: case XmlReadMode.IgnoreSchema: case XmlReadMode.DiffGram: XmlDiffLoader DiffLoader = new XmlDiffLoader (this); DiffLoader.Load (reader); if (mode == XmlReadMode.Auto) result = XmlReadMode.DiffGram; shouldReadData = false; break; case XmlReadMode.Fragment: reader.Skip (); break; default: reader.Skip (); break; } } // if schema after diffgram, just skip it. if (!shouldReadData && reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace) { shouldNotInfer = true; switch (mode) { default: reader.Skip (); break; case XmlReadMode.ReadSchema: case XmlReadMode.DiffGram: if (Tables.Count == 0) ReadXmlSchema (reader); break; } } if (reader.EOF) return result == XmlReadMode.Auto ? potentialDataSetName != null && !shouldNotInfer ? XmlReadMode.InferSchema : XmlReadMode.IgnoreSchema : result; // Otherwise, read as dataset... but only when required. if (shouldReadData && !shouldNotInfer) { switch (mode) { case XmlReadMode.Auto: if (Tables.Count > 0) goto case XmlReadMode.IgnoreSchema; else goto case XmlReadMode.InferSchema; case XmlReadMode.InferSchema: InferXmlSchema (doc, null); if (mode == XmlReadMode.Auto) result = XmlReadMode.InferSchema; break; case XmlReadMode.IgnoreSchema: case XmlReadMode.Fragment: case XmlReadMode.DiffGram: break; default: shouldReadData = false; break; } } if (shouldReadData) { XmlReader dataReader = reader; if (doc != null) { dataReader = new XmlNodeReader (doc); dataReader.MoveToContent (); } if (reader.NodeType == XmlNodeType.Element) XmlDataReader.ReadXml (this, dataReader, mode); } if (skippedTopLevelElement) { switch (result) { case XmlReadMode.Auto: case XmlReadMode.InferSchema: // DataSetName = potentialDataSetName; // result = XmlReadMode.InferSchema; break; } if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement (); } //* while (input.Depth > depth) input.Read (); if (input.NodeType == XmlNodeType.EndElement) input.Read (); //*/ input.MoveToContent (); return result == XmlReadMode.Auto ? XmlReadMode.IgnoreSchema : result; }
/// <summary> /// Captures MSN conversations /// </summary> /// <param name="xmlMessage">xml string containing an IM message data</param> /// <returns>an MSNMessageData struct containing the parsed data</returns> private MSNMessageData ParseMessageData(string xmlMessage) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlMessage); XmlNodeReader reader = new XmlNodeReader(doc); MSNMessageData messageData = new MSNMessageData(); // Moves the reader to the root element. reader.MoveToContent(); // get the date reader.MoveToAttribute("DateTime"); messageData.date = DateTime.Parse(reader.Value); // get the session id reader.MoveToAttribute("SessionID"); messageData.sessionId = Convert.ToInt32(reader.Value); // get the rest of the attributes while (reader.Read()) { // advance to the inner node we're interested in if (reader.NodeType == XmlNodeType.Element) { string parentNodeName = reader.LocalName; reader.Read(); switch(parentNodeName) { case "From": // get the from user reader.MoveToAttribute("FriendlyName"); messageData.fromFriendlyName = reader.Value; break; case "To": // get the to user reader.MoveToAttribute("FriendlyName"); messageData.toFriendlyName = reader.Value; break; // get the actual IM message case "Text": messageData.message = reader.Value; break; default: break; } } } // set user and buddy names if not already set if (userName == null) userName = messageData.fromFriendlyName; if (buddyName == null) buddyName = messageData.toFriendlyName; return messageData; }
/// <summary> /// Get node value by nodename /// </summary> /// <param name="doc"></param> /// <param name="nodeName"></param> /// <param name="nodeAttribute"></param> /// <returns></returns> public string GetNodeValue(XmlDocument doc, string nodeName, params string[] nodeAttribute) { using (XmlNodeReader nodeReader = new XmlNodeReader(doc)) { nodeReader.MoveToContent(); XDocument xmlDoc = XDocument.Load(nodeReader); var result = from c in xmlDoc.Descendants(nodeName) select c; string res = ""; if (nodeAttribute.Length == 0) { foreach (var item in result) { res = item.Value.ToString(); } } else { foreach (var item in result) { res = item.Attribute(nodeAttribute[0]).Value.ToString(); } } return res; } //XDocument xmlDoc = XDocument.Load(path); //XmlNode node = doc.SelectSingleNode("/getPartyDetailResponse/getPartyDetailResult/serviceStatus/overallStatus"); //return node.InnerText; }