/// <summary> /// Converts an XmlDocument into an XDocument. /// </summary> /// <param name="xmlDocument">The XmlDocument to operate on.</param> /// <returns>The converted System.Xml.Linq.XDocument</returns> public static XDocument ToXDocument(this XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader); } }
public XmlReader CreateReader() { #if MOBILE var reader = XmlReader.Create(new StringReader(body)); #else var reader = new XmlNodeReader(body); #endif reader.MoveToContent(); return(reader); }
public static XDocument ToXDocument(this XmlDocument xmlDocument) { Check.Current.ArgumentNullException(xmlDocument, "xmlDocument"); using (var reader = new XmlNodeReader(xmlDocument)) { reader.MoveToContent(); return(XDocument.Load(reader)); } }
XDocument LoadDocument() { XDocument doc = null; using (XmlNodeReader reader = new XmlNodeReader(xmlDataSource.GetXmlDocument())) { reader.MoveToContent(); doc = XDocument.Load(reader); } return(doc); }
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())); }
/// <summary> /// Gets a property value be evaluating an XPath expression on a source XML object. /// Supported source objects are XmlDataProvider, XmlDocument, XDocument. /// </summary> /// <param name="src">The source element</param> /// <param name="xpath">The XPath expression into the source element.</param> /// <returns>The evaluated value</returns> public static object GetPropValueFromXPath(object src, string xpath) { // if the source is null then return null if (src == null) { // could raise some sort of error as the property path is invalid on a null - but this is what WPF bindings do... System.Diagnostics.Debug.Print("Map.GetPropValue failed: XPath='{0}'", xpath); return(null); } try { // try to load the source in a XDocument XDocument doc; if (src is XmlDataProvider) { using (var nodeReader = new XmlNodeReader(((XmlDataProvider)src).Document)) { nodeReader.MoveToContent(); doc = XDocument.Load(nodeReader); } } else if (src is XmlDocument) { using (var nodeReader = new XmlNodeReader((XmlDocument)src)) { nodeReader.MoveToContent(); doc = XDocument.Load(nodeReader); } } else if (src is XDocument) { doc = (XDocument)src; } else { System.Diagnostics.Debug.Print("XPath only supported for src of XmlDataProvider, XmlDocument or XDocument: XPath='{0}', Source={1}", xpath, src); return(null); } var namespaceManager = new XmlNamespaceManager(new NameTable()); var value = doc.XPathSelectElement(xpath, namespaceManager).Value; // will return a date time instance is it is one return(TryForDate(value)); } catch (Exception ex) { System.Diagnostics.Debug.Print("BindingContainer.GetPropValueFromXPath failed: XPath={0}, Source={1}, Error={2}", xpath, src, ex.Message); return(null); } }
/// <summary> /// Returns an XLinq node from the given <see cref="XmlNode"/>. /// </summary> /// <param name="node"></param> /// <returns></returns> public static XNode ToXNode(this XmlNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } var rdr = new XmlNodeReader(node); rdr.MoveToContent(); return(XNode.ReadFrom(rdr)); }
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 static XDocument ToXDocument([NotNull] this XmlDocument document) { if (document is null) { throw new ArgumentNullException(nameof(document)); } using XmlNodeReader reader = new XmlNodeReader(document); reader.MoveToContent(); return(XDocument.Load(reader)); }
public static RbfFile GetRbf(XmlDocument doc) { var rbf = new RbfFile(); using (var reader = new XmlNodeReader(doc)) { reader.MoveToContent(); rbf.current = (RbfStructure)Traverse(XDocument.Load(reader).Root); } return(rbf); }
/// <summary> /// /// </summary> /// <remarks></remarks> /// <seealso cref=""/> /// <param name="xmlDocument"></param> /// <returns></returns> public static XDocument ToXDocument(XmlDocument xmlDocument) { if (xmlDocument != null) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); return(XDocument.Load(nodeReader)); } } return(null); }
/// <summary> /// Convert to <see cref="XDocument"/> /// </summary> /// <param name="xmlDocument"></param> /// <returns></returns> public static XDocument ToXDocument(this XmlDocument xmlDocument) { if (xmlDocument == null) { return(null); } using (var xml = new XmlNodeReader(xmlDocument)) { xml.MoveToContent(); return(XDocument.Load(xml)); } }
private static string ConvertToLowerCaseXml(ContractProcessResult item) { XDocument document = null; using (var reader = new XmlNodeReader(item.ContractXml.DocumentElement.FirstChild)) { reader.MoveToContent(); document = XDocument.Load(reader); } document.LowerCaseAllElementNames(); return(document.Root.ToString()); }
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)); } }
/// <summary> /// Converts the supplied <see cref="XmlDocument"/> instance into an <see cref="XDocument"/> instance. /// </summary> /// <param name="xdocument"><see cref="XmlDocument"/> instance to convert.</param> /// <returns>Converted <see cref="XDocument"/> instance.</returns> public static XDocument ToXDocument(XmlDocument xmlDoc) { XDocument result = null; if (xmlDoc == null) { return(result); } using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDoc)) { xmlNodeReader.MoveToContent(); return(XDocument.Load(xmlNodeReader)); } }
private void GetAppliesToQName(XmlElement rootElement, out string localName, out string namespaceUri) { localName = namespaceUri = null; XmlElement appliesToElement = GetAppliesToElement(rootElement); if (appliesToElement != null) { using (XmlReader reader = new XmlNodeReader(appliesToElement)) { reader.ReadStartElement(); reader.MoveToContent(); localName = reader.LocalName; namespaceUri = reader.NamespaceURI; } } }
/// <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); }
public void parse() { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(a); //x.LoadXml(@"C:\app\vs2019\VC#\mywork\XMLParser\XMLParser\bin\Debug\demo.xml"); Console.WriteLine(formatXml(a)); //Console.WriteLine(x.InnerXml); XmlNodeReader xmlNode = new XmlNodeReader(xdoc.GetElementsByTagName("library")[0]); Console.WriteLine("Node library Value: " + xmlNode.Value); //打印获取值 Console.WriteLine("XmlDocument ChildNodes.Count: " + xdoc.ChildNodes.Count); //打印子节点数量 Console.WriteLine("XmlDocument ChildNodes[0].Name: " + xdoc.ChildNodes[0].Name); //打印节点名称 Console.WriteLine("Node library MoveToContent(): " + xmlNode.MoveToContent()); //如果有下一个节点,直接指向下一个节点 Console.WriteLine("Node library AttributeCount: " + xmlNode.AttributeCount); //打印属性数量 Console.WriteLine("Node library MoveToAttribute(\"id\"): " + xmlNode.MoveToAttribute("id")); //获取该属性节点的值 Console.WriteLine("Node library Value: " + xmlNode.Value); //打印获取值 Console.WriteLine("Node library name: " + xdoc.GetElementsByTagName("library")[0].Name); //打印节点名称 Console.WriteLine("Node library attr id: " + xdoc.GetElementsByTagName("library")[0].Attributes["id"].Value); //打印节点属性值 Console.WriteLine("Node name innertext: " + xdoc.GetElementsByTagName("name")[0].InnerText); //打印节点值 Console.WriteLine("Node name attr count: " + xdoc.GetElementsByTagName("name")[0].Attributes.Count); //打印属性数量 Console.WriteLine("Node name attr txt value: " + xdoc.GetElementsByTagName("name")[0].Attributes["txt"].Value); //打印属性值 Console.WriteLine("XmlDocument Name: " + xdoc.DocumentElement.Name); Console.WriteLine("XmlDocument FirstChild Name: " + xdoc.DocumentElement.FirstChild.Name); XmlNodeList nodeList = xdoc.DocumentElement.ChildNodes; foreach (XmlElement xe in nodeList) { Console.WriteLine(xdoc.DocumentElement.Name + " Child Name:" + xe.Name); } nodeList = xdoc.DocumentElement.FirstChild.ChildNodes; foreach (XmlElement xe in nodeList) { Console.WriteLine(xe.InnerText); if (xe.HasAttributes) { Console.WriteLine(xe.Attributes.Count); for (int i = 0; i < xe.Attributes.Count; i++) { Console.WriteLine(xe.Attributes[i].Name); } Console.WriteLine(xe.Attributes["id"].Value); Console.WriteLine(xe.Attributes["txt"].Value); } } }
public static void Main() { XmlNodeReader reader = null; try { //Create and load an XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" + "<book>" + "<title>Pride And Prejudice</title>" + "<misc>&h;</misc>" + "</book>"); //Create the reader. reader = new XmlNodeReader(doc); reader.MoveToContent(); //Move to the root element. reader.Read(); //Move to title start tag. reader.Skip(); //Skip the title element. //Read the misc start tag. The reader is now positioned on //the entity reference node. reader.ReadStartElement(); //You must call ResolveEntity to expand the entity reference. //The entity replacement text is then parsed and returned as a child node. Console.WriteLine("Expand the entity..."); reader.ResolveEntity(); Console.WriteLine("The entity replacement text is returned as a text node."); reader.Read(); Console.WriteLine("NodeType: {0} Value: {1}", reader.NodeType, reader.Value); Console.WriteLine("An EndEntity node closes the entity reference scope."); reader.Read(); Console.WriteLine("NodeType: {0} Name: {1}", reader.NodeType, reader.Name); } finally { if (reader != null) { reader.Close(); } } }
/// <summary> /// json type string To XDocument /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public static XDocument jsonToXDocument(this string jsonString) { try { XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonString); using (var nodeReader = new XmlNodeReader(doc)) { nodeReader.MoveToContent(); return(XDocument.Load(nodeReader)); } } catch (Exception ex) { throw ex; } }
public void Load(XmlDocument doc) { Clear(); XmlNodeReader nodeReader = new XmlNodeReader(doc); nodeReader.MoveToContent(); XDocument dict = XDocument.Load(nodeReader); XElement plist = dict.Element(TYPE_PLIST); var plisElements = plist.Elements(); ParseDictForLoad(this, plisElements); nodeReader.Close(); }
public XmlActionResult(XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); _document = XDocument.Load(nodeReader); } if (_document == null) { throw new ArgumentNullException("document"); } // Default values MimeType = "text/xml"; Formatting = Formatting.None; }
public void ParseXML(string AHSoapRequest) { try { AHDocument.LoadXml(AHSoapRequest); using (var nodeReader = new XmlNodeReader(AHDocument)) { nodeReader.MoveToContent(); xAHDocument = XDocument.Load(nodeReader); Paths = xAHDocument.Root.DescendantNodesAndSelf().OfType <XElement>().Where(y => y.HasElements == false && !y.IsEmpty).Select(x => x.Name).Distinct(); } LAF.Clear(); foreach (XName XN in Paths) { IEnumerable <XElement> XE = xAHDocument.DescendantNodes().OfType <XElement>().Where(x => x.Name == XN); if (XE.Count() > 0) { foreach (XElement X in XE) { if (X.Name.ToString().Contains("name")) { string FName = X.ToString().Substring(X.ToString().IndexOf('>') + 1); string Name = FName.Substring(0, FName.IndexOf('<')); XElement NodeValue = (XElement)X.NextNode; string Value = NodeValue.Value; LAF.Add(new LabelAndField(Name, Value, true, true, X.Name.ToString())); } else if (!X.Name.ToString().Contains("value")) { string FName = X.Name.ToString().Substring(X.Name.ToString().IndexOf('}') + 1); LAF.Add(new LabelAndField(FName, X.Value, true, true, X.Name.ToString())); } } } else { LAF.Add(new LabelAndField(XE.First().Name.ToString(), XE.First().Value, true, true)); } } } catch (XmlException E) { Console.WriteLine(E.Message); } }
public static bool CompareXml(XmlDocument actualXml, XmlDocument expectedXml, out XmlDocument diffGramXml) { Func <XmlDocument, string> prettyPrint = (xml) => { using (var nodeReader = new XmlNodeReader(xml)) { nodeReader.MoveToContent(); return(XDocument.Load(nodeReader).ToString()); } }; using (XmlReader actualReader = new XmlNodeReader(actualXml)) { using (XmlReader expectedReader = new XmlNodeReader(expectedXml)) { var xmlDiff = new XmlDiff(XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnoreXmlDecl | XmlDiffOptions.IgnoreChildOrder); diffGramXml = new XmlDocument(); using (var diffGramWriter = diffGramXml.CreateNavigator().AppendChild()) { var identical = xmlDiff.Compare(actualReader, expectedReader, diffGramWriter); diffGramWriter.Close(); if (!identical) { Console.WriteLine("Diff gram:"); Console.WriteLine(prettyPrint(diffGramXml)); Console.WriteLine(); Console.WriteLine("Expected:"); Console.WriteLine(prettyPrint(expectedXml)); Console.WriteLine(); Console.WriteLine("Actual:"); Console.WriteLine(prettyPrint(actualXml)); Console.WriteLine(); } return(identical); } } } }
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.ToPhysicalDeployElement(xRoot); } if (result != null) { SaveFileDialog sfd = new SaveFileDialog(); sfd.DefaultExt = "xml"; string sourcepath = txtFileName.Text; FileInfo file = new FileInfo(sourcepath); sfd.InitialDirectory = file.DirectoryName; sfd.FileName = Path.Combine(file.DirectoryName, "AppDeploy.xml"); 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); } }
private XDocument SignXml(XDocument xDocument) { XmlDocument xmlDocument = new XmlDocument(); using (XmlReader xmlReader = xDocument.CreateReader()) { xmlDocument.Load(xmlReader); } SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = _certificate.PrivateKey; Reference reference = new Reference(); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(_certificate); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true)); using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); xDocument = XDocument.Load(nodeReader); } return(xDocument); }
/// <summary> /// Converts an MLDocument object to an XDocument object /// </summary> /// <param name="xmlDocument">The XMLDocument to be converted.</param> /// <returns>An XDocument contianing the contents of the XmlDocument.</returns> /// Contributed by Russell Dehart public static XDocument ToXDocument(this XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { try { nodeReader.MoveToContent(); } catch (XmlException) { throw; } catch (System.InvalidOperationException) { throw; } return(XDocument.Load(nodeReader)); } }
public static void Main() { XmlNodeReader reader = null; try { //Create and load an XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'harcover'>]>" + "<book genre='novel' misc='sale-item &h; 1987'>" + "</book>"); //Create the reader. reader = new XmlNodeReader(doc); //Read the misc attribute. The attribute is parsed into multiple //text and entity reference nodes. reader.MoveToContent(); reader.MoveToAttribute("misc"); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { //To expand the entity, call ResolveEntity. Console.WriteLine("{0} {1}", reader.NodeType, reader.Name); } else { Console.WriteLine("{0} {1}", reader.NodeType, reader.Value); } } } finally { if (reader != null) { reader.Close(); } } }
/// <summary> /// Function to load the local confg file /// </summary> private void InitializeKeys() { string XML_NODE_NAME_ELEMENT = "add"; string XML_NODE_NAME_KEY = "key"; string XML_NODE_NAME_VALUE = "value"; XmlDocument xmldoc = new XmlDocument(); //open the xml file and traverse till the appropriate node in it. FileStream fs = new FileStream("App.config", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); XmlNode xmlnode = xmldoc.GetElementsByTagName("Server")[0]; //read the key values and store them in local variable. using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlnode)) { if (null != xmlNodeReader) { // Move to first content node (like element node) xmlNodeReader.MoveToContent(); while (xmlNodeReader.Read()) { if (xmlNodeReader.Name == XML_NODE_NAME_ELEMENT) { //Read the key from the attribute string key = xmlNodeReader.GetAttribute(XML_NODE_NAME_KEY); string value = xmlNodeReader.GetAttribute(XML_NODE_NAME_VALUE); if (!string.IsNullOrEmpty(key)) { _serverConfiguration[key] = value; } } } } fs.Flush(); fs.Close(); xmlnode = null; } }
public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78'> " + "<title>Pride And Prejudice</title>" + "<price>19.95</price>" + "</book>"); //Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the attributes on the book element. reader.MoveToContent(); while (reader.MoveToNextAttribute()) { Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Move the reader to the title element. reader.Read(); //Read the title and price elements. Console.WriteLine(reader.ReadElementString()); Console.WriteLine(reader.ReadElementString()); } finally { if (reader != null) { reader.Close(); } } }
List <string> ThesaurusParse(string xml) { List <string> synonyms = new List <string>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlReader reader = new XmlNodeReader(doc); while (reader.ReadToFollowing("w") && synonyms.Count < synonymNumber) { reader.MoveToAttribute("r"); string type = reader.Value; reader.MoveToContent(); string result = reader.ReadInnerXml(); if (type == "syn") { synonyms.Add(result); } } return(synonyms); }