public CreateDocumentFragment ( ) : |
||
Résultat |
public static TwoTransparent2 Create() { TwoTransparent2 ttxf = new TwoTransparent2(); XmlDocument doc = new XmlDocument(); ttxf._frag = doc.CreateDocumentFragment(); ttxf._frag2 = doc.CreateDocumentFragment(); ttxf._frag2.AppendChild( doc.CreateElement( "sub2" ) ).InnerText = "3"; ttxf._frag2.AppendChild( doc.CreateElement( "sub2" ) ).InnerText = "4"; return ttxf; }
public static TwoTransparentXmlFragments Create2() { TwoTransparentXmlFragments ttxf = new TwoTransparentXmlFragments(); ttxf.elem1 = null; ttxf.elem3 = null; XmlDocument doc = new XmlDocument(); ttxf._frag = doc.CreateDocumentFragment(); ttxf._frag2 = doc.CreateDocumentFragment(); ttxf._frag2.AppendChild( doc.CreateElement( "sub2" ) ).InnerText = "3"; ttxf._frag2.AppendChild( doc.CreateElement( "sub2" ) ).InnerText = "4"; return ttxf; }
public XmlNode SerializeAsXmlNode(XmlDocument doc) { System.IO.MemoryStream ms = new MemoryStream(); XmlSerializer serializer = new XmlSerializer(typeof(ColumnCollection)); XmlTextReader xRead = null; XmlNode xTable = null; try { xTable = doc.CreateNode(XmlNodeType.Element, "TABLE", doc.NamespaceURI); serializer.Serialize(ms, this); ms.Position = 0; xRead = new XmlTextReader( ms ); xRead.MoveToContent(); string test = xRead.ReadInnerXml(); XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = test; xTable.AppendChild(docFrag); } catch(Exception ex) { throw new Exception("IdentityCollection Serialization Error.", ex); } finally { ms.Close(); if (xRead != null) xRead.Close(); } return xTable; }
public ControlResponse GetResponse(Exception ex) { var env = new XmlDocument(); env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", "yes")); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); var fault = env.CreateElement("SOAP-ENV", "Fault", NS_SOAPENV); var faultCode = env.CreateElement("faultcode"); faultCode.InnerText = "500"; fault.AppendChild(faultCode); var faultString = env.CreateElement("faultstring"); faultString.InnerText = ex.ToString(); fault.AppendChild(faultString); var detail = env.CreateDocumentFragment(); detail.InnerXml = "<detail><UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\"><errorCode>401</errorCode><errorDescription>Invalid Action</errorDescription></UPnPError></detail>"; fault.AppendChild(detail); rbody.AppendChild(fault); return new ControlResponse { Xml = env.OuterXml, IsSuccessful = false }; }
public static void CheckNodeType() { var xmlDocument = new XmlDocument(); var documentFragment = xmlDocument.CreateDocumentFragment(); Assert.Equal(XmlNodeType.DocumentFragment, documentFragment.NodeType); }
public static void AddHeaderInformation(XmlDocument xmlDoc, QMaker qMaker) { StringBuilder sbH = new StringBuilder(); StringWriter tempWriterH = new StringWriter(sbH); XmlTextWriter writerH = new XmlTextWriter(tempWriterH); writerH.WriteStartElement("Headers"); foreach (QField gField in qMaker.Groups) { writerH.WriteStartElement("Header"); writerH.WriteAttributeString("Name", gField.Name); writerH.WriteAttributeString("Description", gField.FriendlyName); writerH.WriteEndElement();//Header } foreach (QField fField in qMaker.Fields) { writerH.WriteStartElement("Header"); writerH.WriteAttributeString("Name", fField.Name); writerH.WriteAttributeString("Description", fField.FriendlyName); writerH.WriteEndElement();//Header } writerH.WriteEndElement();//Headers writerH.Flush(); XmlDocumentFragment xmlHeaders = xmlDoc.CreateDocumentFragment(); xmlHeaders.InnerXml = sbH.ToString(); xmlDoc.SelectSingleNode("Report").AppendChild(xmlHeaders); }
void Add(XmlDocument docFrom,XmlDocument docTo,string id/*,string text*/) { XmlNodeList nodeList = docFrom.SelectNodes("root/tablename[@ID='"+id+"']"); string [] text = new string[nodeList.Count]; foreach(XmlNode curNode in nodeList) { string curText = curNode.Attributes["Text"].Value; Match match = Regex.Match(curText,"\\\\\\d+$"); int index = 0; if(match.Success) index = int.Parse(match.Value.Substring(1)); text[index] = curText; docFrom.DocumentElement.RemoveChild(curNode); } XmlDocumentFragment docFrag = docTo.CreateDocumentFragment(); XmlNode parentNode = docFrag; foreach(string str in text) { XmlElement newNode = docTo.CreateElement("treenode"); newNode.SetAttribute("text",str); parentNode.AppendChild(newNode); parentNode = newNode; } docTo.DocumentElement.AppendChild(docFrag); }
public static void GetAttributesOnDocumentFragment() { var xmlDocument = new XmlDocument(); var documentFragment = xmlDocument.CreateDocumentFragment(); Assert.Null(documentFragment.Attributes); }
/// <summary> /// Replaces the read-only Word content controls with XWiki macro markup. /// </summary> /// <param name="xmlDoc">A reference to the xml document instance.</param> public void Filter(ref XmlDocument xmlDoc) { XmlNodeList macroNodes = xmlDoc.GetElementsByTagName("Sdt", "urn:schemas-microsoft-com:office:word"); XmlDocumentFragment docFrag = xmlDoc.CreateDocumentFragment(); Dictionary<String, String> macros = this.manager.States.Macros; //We use a new list because the XmlNodeList will break when operationg with its' elements. List<XmlNode> nodeList = new List<XmlNode>(); foreach (XmlNode node in macroNodes) { nodeList.Add(node); } foreach (XmlNode node in nodeList) { try { String id = node.Attributes["ID"].Value; if (macros.ContainsKey(id)) { String content = macros[id]; docFrag.InnerXml = content; node.ParentNode.ReplaceChild(docFrag, node); } } catch (NullReferenceException nre) { Log.Exception(nre); } catch (Exception ex) { Log.Exception(ex); } } }
public void Constructor () { XmlDocument d = new XmlDocument (); XmlDocumentFragment df = d.CreateDocumentFragment (); AssertEquals ("#Constructor.NodeName", "#document-fragment", df.Name); AssertEquals ("#Constructor.NodeType", XmlNodeType.DocumentFragment, df.NodeType); }
public static XmlNode ToXml(this string xml) { var doc = new XmlDocument(); var fragment = doc.CreateDocumentFragment(); fragment.InnerXml = xml; doc.AppendChild(fragment); return doc.FirstChild; }
// Clone this document fragment node. public override XmlNode CloneNode(bool deep) { XmlDocumentFragment frag = document.CreateDocumentFragment(); frag.CloneChildrenFrom(this, deep); return(frag); }
// It should be public after some tests are done :-) public XmlNodeWriter (bool isDocumentEntity) { doc = new XmlDocument (); state = XmlNodeType.None; this.isDocumentEntity = isDocumentEntity; if (!isDocumentEntity) current = fragment = doc.CreateDocumentFragment (); }
// It should be public after some tests are done :-) public XmlNodeWriter(bool isDocumentEntity) { doc = new XmlDocument(); state = XmlNodeType.None; this.isDocumentEntity = isDocumentEntity; if (!isDocumentEntity) { current = fragment = doc.CreateDocumentFragment(); } }
public static void OnDocumentFragment() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/>some text<child2/><child3/></root>"); var documentFragment = xmlDocument.CreateDocumentFragment(); documentFragment.AppendChild(xmlDocument.DocumentElement); Assert.Null(documentFragment.NextSibling); }
public TransparentXmlFragment( bool init ) { elem1 = "3"; elem3 = "4"; XmlDocument doc = new XmlDocument(); _frag = doc.CreateDocumentFragment(); XmlNode node = _frag.AppendChild( doc.CreateElement( "sub1" ) ); node.AppendChild( doc.CreateElement( "extra" ) ); _frag.AppendChild( doc.CreateElement( "sub2" ) ).InnerText = "2"; }
public void SetInnerXml () { document = new XmlDocument (); fragment = document.CreateDocumentFragment (); fragment.InnerXml = "<foo /><bar><child /></bar><baz />"; AssertEquals ("foo", fragment.FirstChild.Name); AssertEquals ("bar", fragment.FirstChild.NextSibling.Name); AssertEquals ("child", fragment.FirstChild.NextSibling.FirstChild.Name); AssertEquals ("baz", fragment.LastChild.Name); }
public override XmlNode CloneNode(bool deep) { XmlDocument ownerDocument = this.OwnerDocument; XmlDocumentFragment fragment = ownerDocument.CreateDocumentFragment(); if (deep) { fragment.CopyChildren(ownerDocument, this, deep); } return(fragment); }
public void GetInnerXml () { // this will be also tests of TestWriteTo()/TestWriteContentTo() document = new XmlDocument (); fragment = document.CreateDocumentFragment (); fragment.AppendChild (document.CreateElement ("foo")); fragment.AppendChild (document.CreateElement ("bar")); fragment.AppendChild (document.CreateElement ("baz")); AssertEquals ("#Simple", "<foo /><bar /><baz />", fragment.InnerXml); }
public static void GenerateLicense(int months) { // The license key, it must be 20 bytes long to be compatible with RSA string licenseKey = DateTime.Now.Date.AddMonths(months).ToShortDateString(); // If a current license exists, add the new license length onto the old one. if (File.Exists(Environment.CurrentDirectory + @"\licenseinfo.xml")) { XmlDocument licenseFile = new XmlDocument(); licenseFile.Load(Environment.CurrentDirectory + @"\licenseinfo.xml"); string savedLicenseKey = licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/KEY").InnerText; string licenseExpiry = savedLicenseKey.Substring(0, savedLicenseKey.LastIndexOf(@"/") + 5); if (Convert.ToDateTime(licenseExpiry) > DateTime.Today) { licenseKey = (Convert.ToDateTime(licenseExpiry).AddMonths(months)).ToShortDateString(); } } string machineName = Environment.MachineName; licenseKey += machineName; // Adds trailing 0's if the date+machinename is less than 20 charachters while (licenseKey.Length < 20) { licenseKey += "0"; } // Cuts the key down to 20 charachters if the date+machinename are too large. licenseKey = licenseKey.Substring(0, 20); // Byte arrays to store the license key byte[] byteLicenseKey = Encoding.ASCII.GetBytes(licenseKey); // The RSA handling and public key creation RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(RSA); rsaFormatter.SetHashAlgorithm("SHA1"); string publicKey = RSA.ToXmlString(false); // The digital signature for the license byte[] digitalSignature = rsaFormatter.CreateSignature(byteLicenseKey); //An XML file that holds the public key, license key, and the Digital Signature XmlDocument licenseDocument = new XmlDocument(); XmlElement parentNode = licenseDocument.CreateElement("LicenseInfo"); licenseDocument.AppendChild(parentNode); XmlElement xmlDocLicenseKey = licenseDocument.CreateElement("KEY"); xmlDocLicenseKey.InnerText = Encoding.Default.GetString(byteLicenseKey); parentNode.AppendChild(xmlDocLicenseKey); XmlElement xmlDocLicenseSignature = licenseDocument.CreateElement("SignedKey"); xmlDocLicenseSignature.InnerText = Convert.ToBase64String(digitalSignature); parentNode.AppendChild(xmlDocLicenseSignature); XmlDocumentFragment publicKeyNode = licenseDocument.CreateDocumentFragment(); publicKeyNode.InnerXml = publicKey; parentNode.AppendChild(publicKeyNode); licenseDocument.Save(Environment.CurrentDirectory + @"\licenseinfo.xml"); }
public static void EmptyWork() { var xmlDocument = new XmlDocument(); var xml = "<root>\r\n text node one\r\n <elem1 child1=\"\" child2=\"duu\" child3=\"e1;e2;\" child4=\"a1\" child5=\"goody\">\r\n text node two e1; text node three\r\n </elem1><!-- comment3 --><?PI3 processing instruction?>e2;<foo /><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"><a /></elem2><elem2> \r\n elem2-text1\r\n <a> \r\n this-is-a \r\n </a> \r\n\r\n elem2-text2\r\n e3;e4;<!-- elem2-comment1-->\r\n elem2-text3\r\n\r\n <b> \r\n this-is-b\r\n </b>\r\n\r\n elem2-text4\r\n <?elem2_PI elem2-PI?>\r\n elem2-text5\r\n\r\n </elem2></root>"; xmlDocument.LoadXml(xml); foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes) Assert.Equal(String.Empty, node.Prefix); Assert.Equal(String.Empty, xmlDocument.CreateDocumentFragment().Prefix); }
// Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); XmlDocument doc = OwnerDocument; XmlDocumentFragment clone = doc.CreateDocumentFragment(); if (deep) { clone.CopyChildren(doc, this, deep); } return(clone); }
public void AppendChildToFragment () { document = new XmlDocument (); fragment = document.CreateDocumentFragment (); document.LoadXml ("<html><head></head><body></body></html>"); XmlElement el = document.CreateElement ("p"); el.InnerXml = "Test Paragraph"; // appending element to fragment fragment.AppendChild (el); AssertNotNull ("#AppendChildToFragment.Element", fragment.FirstChild); AssertNotNull ("#AppendChildToFragment.Element.Children", fragment.FirstChild.FirstChild); AssertEquals ("#AppendChildToFragment.Element.Child.Text", "Test Paragraph", fragment.FirstChild.FirstChild.Value); }
internal void AddDeviceStatusToLog(string comment) { string frag = "<DeviceStatus><Text>" + ConvertUnsafeXmlStrings(comment) + "</Text><Date></Date><Time></Time></DeviceStatus>"; XmlDocument doc = new XmlDocument(); doc.Load(m_logFile); XmlNode node = doc.SelectSingleNode("/SPOT_Platform_Test"); XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = frag; node.AppendChild(docFrag); doc.Save(m_logFile); }
public static void ImportDocumentFragment() { var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateDocumentFragment(); nodeToImport.AppendChild(tempDoc.CreateElement("A1")); nodeToImport.AppendChild(tempDoc.CreateComment("comment")); nodeToImport.AppendChild(tempDoc.CreateProcessingInstruction("PI", "donothing")); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); Assert.Equal(XmlNodeType.DocumentFragment, node.NodeType); Assert.Equal(nodeToImport.OuterXml, node.OuterXml); }
public void AppendFragmentToElement () { document = new XmlDocument (); fragment = document.CreateDocumentFragment (); document.LoadXml ("<html><head></head><body></body></html>"); XmlElement body = document.DocumentElement.LastChild as XmlElement; fragment.AppendChild (document.CreateElement ("p")); fragment.AppendChild (document.CreateElement ("div")); // appending fragment to element body.AppendChild (fragment); AssertNotNull ("#AppendFragmentToElement.Exist", body.FirstChild); AssertEquals ("#AppendFragmentToElement.ChildIsElement", XmlNodeType.Element, body.FirstChild.NodeType); AssertEquals ("#AppendFragmentToElement.FirstChild", "p", body.FirstChild.Name); AssertEquals ("#AppendFragmentToElement.LastChild", "div", body.LastChild.Name); }
public static void OwnerDocumentOnImportedTree() { var tempDoc = new XmlDocument(); var nodeToImport = tempDoc.CreateDocumentFragment(); nodeToImport.AppendChild(tempDoc.CreateElement("A1")); nodeToImport.AppendChild(tempDoc.CreateComment("comment")); nodeToImport.AppendChild(tempDoc.CreateProcessingInstruction("PI", "donothing")); var xmlDocument = new XmlDocument(); var node = xmlDocument.ImportNode(nodeToImport, true); Assert.Equal(xmlDocument, node.OwnerDocument); foreach (XmlNode child in node.ChildNodes) Assert.Equal(xmlDocument, child.OwnerDocument); }
public void AppendFragmentToElement () { document = new XmlDocument (); fragment = document.CreateDocumentFragment (); document.LoadXml ("<html><head></head><body></body></html>"); XmlElement body = document.DocumentElement.LastChild as XmlElement; fragment.AppendChild (document.CreateElement ("p")); fragment.AppendChild (document.CreateElement ("div")); // appending fragment to element XmlNode ret = body.AppendChild (fragment); Assert.IsNotNull (body.FirstChild, "#AppendFragmentToElement.Exist"); Assert.AreEqual (XmlNodeType.Element, body.FirstChild.NodeType, "#AppendFragmentToElement.ChildIsElement"); Assert.AreEqual ("p", body.FirstChild.Name, "#AppendFragmentToElement.FirstChild"); Assert.AreEqual ("div", body.LastChild.Name, "#AppendFragmentToElement.LastChild"); Assert.AreEqual ("p", ret.LocalName, "#AppendFragmentToElement.ReturnValue"); }
public void XacNhanDiLam(string MaNhanVien, int Ngay, int Thang, int Nam) { XmlTextReader textread = new XmlTextReader("ChamCong.xml"); XmlDocument doc = new XmlDocument(); doc.Load(textread); textread.Close(); XmlNode currNode; XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); docFrag.InnerXml = "<ChamCong>" + "<MaNhanVien>" + MaNhanVien + "</MaNhanVien>" + "<Ngay>" + Ngay + "</Ngay>" + "<Thang>" + Thang + "</Thang>" + "<Nam>" + Nam + "</Nam>" + "</ChamCong>"; currNode = doc.DocumentElement; currNode.InsertAfter(docFrag, currNode.LastChild); doc.Save("ChamCong.xml"); }
public void DocumentFragmentSerialize() { XmlDocument doc = new XmlDocument(); XmlDocumentFragment fragement = doc.CreateDocumentFragment(); fragement.InnerXml = "<Item>widget</Item><Item>widget</Item>"; string jsonText = JavaScriptConvert.SerializeXmlNode(fragement); string expected = @"{""Item"":[""widget"",""widget""]}"; Assert.AreEqual(expected, jsonText); Console.WriteLine("DocumentFragmentSerialize"); Console.WriteLine(jsonText); Console.WriteLine(); }
private void _addExamineProvider() { var xd = new XmlDocument(); xd.Load(_examineIndexConfigFilename); var provider = xd.SelectSingleNode("//ExamineIndexProviders/providers"); var newXml = xd.CreateDocumentFragment(); newXml.InnerXml = @"<add name=""BookshelfIndexer"" type=""Examine.LuceneEngine.Providers.SimpleDataIndexer, Examine"" dataService=""UmbracoBookshelf.Examine.BookshelfExamineDataService,UmbracoBookshelf"" indexTypes=""Bookshelf""/>"; provider.AppendChild(newXml); newXml = xd.CreateDocumentFragment(); newXml.InnerXml = @"<add name=""BookshelfSearcher"" type=""Examine.LuceneEngine.Providers.LuceneSearcher, Examine"" analyzer=""Lucene.Net.Analysis.Standard.StandardAnalyzer, Lucene.Net"" />"; provider = xd.SelectSingleNode("//ExamineSearchProviders/providers"); provider.AppendChild(newXml); xd.Save(_examineIndexConfigFilename); var indexFilename = IOHelper.MapPath("~/config/ExamineIndex.config"); xd.Load(indexFilename); var indexSets = xd.SelectSingleNode("//ExamineLuceneIndexSets"); newXml = xd.CreateDocumentFragment(); newXml.InnerXml = @"<IndexSet SetName=""BookshelfIndexSet"" IndexPath=""~/App_Data/TEMP/ExamineIndexes/Bookshelf""> <IndexUserFields> <add Name=""id""/> <add Name=""book""/> <add Name=""path""/> <add Name=""title""/> <add Name=""text""/> <add Name=""url""/> </IndexUserFields> </IndexSet>"; indexSets.AppendChild(newXml); xd.Save(indexFilename); }
public static void insertXMLSongInfo(string albumName, string albumId, string songName, string songLength, string trackNumber, string genre, string tagName, ref string songId) { XmlDocument doc = new XmlDocument(); XmlNodeList node = null; XmlNode insertNode = doc.CreateDocumentFragment(); int newSongID = 0; //int newAlbumId = 0; try { doc.Load(HttpContext.Current.Server.MapPath("~/DataSource/SongInventory.xml")); if (doc != null) { if (tagName.Equals(@"song")) node = doc.SelectNodes(@"//album" + @"[@Id = '" + albumId + "']"); newSongID = ConfigurationManager.AppSettings[@"songLastId"] != null ? Convert.ToInt32(ConfigurationManager.AppSettings[@"songLastId"]) : 0; if (node.Count > 0) { insertNode.InnerXml = @"<" + tagName + " Title = \"" + songName + "\" Length = \"" + songLength + "\" SongId = \"" + newSongID + "\" TrackNumber = \"" + trackNumber + "\" Genre = \"" + genre + "\"/>"; node[0].AppendChild(insertNode); songId = newSongID.ToString(); webConfigUpdate.AppSettings.Settings[@"songLastId"].Value = Convert.ToString(newSongID+1); webConfigUpdate.AppSettings.Settings["recentXMLDataSourceModify"].Value = DateTime.Now.ToString(); webConfigUpdate.Save(); } else { songId = "-1"; } doc.Save(HttpContext.Current.Server.MapPath("~/DataSource/SongInventory.xml")); } else { throw new Exception("No album exist in the Source File."); } } catch (Exception e) { throw e.InnerException; } }
static XmlDocument RemoveHeader(XmlDocument doc) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; var stringWriter = new StringWriter(); var writer = XmlWriter.Create(stringWriter, settings); doc.Save(writer); XmlDocument docResult = new XmlDocument(); var objElem = docResult.CreateElement("Object"); objElem.SetAttribute("Id", "FATCA"); docResult.AppendChild(objElem); XmlDocumentFragment xfrag = docResult.CreateDocumentFragment(); xfrag.InnerXml = stringWriter.ToString(); docResult.DocumentElement.AppendChild(xfrag); //docResult.LoadXml(stringWriter.ToString()); Console.WriteLine(docResult.OuterXml); return docResult; }
/// <summary> /// Creates an assembly XML document. /// </summary> /// <param name="xmlDocument">The raw XML document to wrap.</param> public XmlAssemblyDocument(XmlDocument xmlDocument) { if (xmlDocument == null) throw new ArgumentNullException("xmlDocument"); Contract.EndContractBlock(); Parser = XmlDocParser.Default; var members = xmlDocument.SelectNodes("/doc/members/member"); if (null != members) { foreach (var member in members.Cast<XmlElement>()) { var subElements = member.ChildNodes.OfType<XmlElement>().ToList(); foreach (var subElement in subElements) { var replacement = xmlDocument.CreateDocumentFragment(); replacement.InnerXml = TextUtility.NormalizeAndUnindentElement(subElement.OuterXml) + "\n"; Contract.Assume(null != subElement.ParentNode); subElement.ParentNode.ReplaceChild(replacement, subElement); } } } XmlDocument = xmlDocument; }
private static IEnumerable ExpandIncludeNode(XmlDocument ownerDocment, string baseDirectory, List <string> parentFileList, List <string> includeFileList, XmlElement element) { string includeFileName = element.GetAttribute(PathToken); if (String.IsNullOrEmpty(includeFileName)) { return new XmlNode[] { } } ; if (!String.IsNullOrEmpty(baseDirectory) && !Path.IsPathRooted(includeFileName)) { includeFileName = Path.Combine(baseDirectory, includeFileName); } if (!String.IsNullOrEmpty(baseDirectory) && IsCircularFileExists(parentFileList, includeFileName)) { throw new XmlException(String.Format("Circular reference encountered on the {0} file.", baseDirectory)); } if (!includeFileList.Contains(includeFileName)) { includeFileList.Add(includeFileName); } XmlDocumentFragment fragment = ownerDocment.CreateDocumentFragment(); try { XmlDocument includeDoc = new XmlDocument(); includeDoc.Load(includeFileName); foreach (XmlAttribute attr in element.Attributes) { if (attr.Name != PathToken) { includeDoc.DocumentElement.SetAttribute(attr.Name, attr.Value); } } fragment.InnerXml = includeDoc.InnerXml; return(new XmlNode[] { fragment.SelectSingleNode("/*") }); } catch (XmlException) { try { using (StreamReader sr = File.OpenText(includeFileName)) fragment.InnerXml = sr.ReadToEnd(); return(fragment.SelectNodes("/*|/comment()")); } catch (Exception innerEx) { throw new XmlException(String.Format("{0}: Error loading xml file.", includeFileName), innerEx); } } catch (Exception ex) { throw new XmlException(String.Format("{0}: Error loading xml file.", includeFileName), ex); } }
public static System.Xml.XmlDocument GetFiltersXmlDocument(string filters) { //string pattern1 = @"((?<op>(AND)|(OR)|(\|\|)|(\&\&)))\s*\("; //string pattern2 = @"\)"; //string pattern3 = @"\("; string opPattern = @"\s*(\>=|\<=|BETWEEN|IS NULL|\!=|==|\<|\>|=)\s*"; //string ltPattern = @"\s*\<\s*"; //string ltEqPattern = @"\s*\<=\s*"; //string gtPattern = @"\s*\>\s*"; //string gtEqPattern = @"\s*\>=\s*"; string filtersXmlString = string.Empty; //filtersXmlString = Regex.Replace(filters, ltPattern, " <", RegexOptions.IgnoreCase); //filtersXmlString = Regex.Replace(filtersXmlString, gtPattern, " >", RegexOptions.IgnoreCase); //filtersXmlString = Regex.Replace(filtersXmlString, pattern1, OPEN_C_TAG + OPEN_OP_TAG + "${op}" + CLOSE_OP_TAG + OPEN_TEXT_TAG, RegexOptions.IgnoreCase); //filtersXmlString = Regex.Replace(filtersXmlString, pattern2, CLOSE_TEXT_TAG + CLOSE_C_TAG); //filtersXmlString = Regex.Replace(filtersXmlString, pattern3, OPEN_OP_TAG + CLOSE_OP_TAG + OPEN_C_TAG + OPEN_TEXT_TAG); //filtersXmlString = filtersXmlString.Replace("&&", "&&"); //if (filtersXmlString.Contains(OPEN_C_TAG)) // filtersXmlString = OPEN_C_TAG + filtersXmlString + CLOSE_C_TAG; //else // filtersXmlString = OPEN_C_TAG + OPEN_TEXT_TAG + filtersXmlString + CLOSE_TEXT_TAG + CLOSE_C_TAG; filtersXmlString = PrepareFiltersXmlString(filters); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(filtersXmlString); foreach (System.Xml.XmlNode node in doc.SelectNodes("//Text")) { if (node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == System.Xml.XmlNodeType.Text) { node.InnerXml = OPEN_C_TAG + ParseCondition(System.Uri.UnescapeDataString(node.InnerXml)) + CLOSE_C_TAG; } } filtersXmlString = doc.InnerXml; filtersXmlString = filtersXmlString.Replace("<Text>", string.Empty);; filtersXmlString = filtersXmlString.Replace("</Text>", string.Empty);; doc.InnerXml = filtersXmlString; string[] arr; System.Xml.XmlDocumentFragment frag; string xmlFrag = string.Empty; bool bContinue = false; Match m; System.Xml.XmlNode tn; string nodeText; foreach (System.Xml.XmlNode n in doc.SelectNodes("//C")) { tn = n.SelectSingleNode("text()"); if (tn != null) { nodeText = System.Uri.UnescapeDataString(tn.InnerText); m = Regex.Match(nodeText, opPattern, RegexOptions.IgnoreCase); if (m.Success) { arr = Regex.Split(nodeText, opPattern, RegexOptions.IgnoreCase); bContinue = false; switch (arr.Length) { case 0: break; case 2: xmlFrag = OPEN_N_TAG + arr[0].Trim() + CLOSE_N_TAG + OPEN_COP_TAG + arr[1].Trim() + CLOSE_COP_TAG; bContinue = true; break; case 3: xmlFrag = OPEN_N_TAG + arr[0].Trim() + CLOSE_N_TAG + OPEN_COP_TAG + Condition.GetComparisonOperator(arr[1]).ToString() + CLOSE_COP_TAG + OPEN_V1_TAG + arr[2].Trim() + CLOSE_V1_TAG; bContinue = true; break; default: break; } if (bContinue && !string.IsNullOrEmpty(xmlFrag)) { frag = doc.CreateDocumentFragment(); frag.InnerXml = xmlFrag; n.ReplaceChild(frag, tn); } } } } foreach (System.Xml.XmlNode n in doc.SelectNodes("//Op")) { if (string.IsNullOrEmpty(n.InnerText.Trim())) { n.InnerText = "None"; } //n.InnerText = ((BinaryOperators)Enum.Parse(typeof(BinaryOperators), n.InnerText.Trim(), true)).ToString(); n.InnerText = Condition.GetBinaryOperator(n.InnerText.Trim()).ToString(); } return(doc); }
public static void Main(string[] args) { string m = "<ArrayOfDataMaskResponse><DataMaskResponse><name>AHA</name><value>1</value><Message>DRM/DPM tag inserted/updated successfully.</Message><Code>0</Code></DataMaskResponse><DataMaskResponse><name>Certegy Restricted</name><value>1</value><Message>DRM/DPM tag inserted/updated successfully.</Message><Code>0</Code></DataMaskResponse></ArrayOfDataMaskResponse>"; System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); //xmlDoc.LoadXml(RIAG.MBS.WS.Utils.SerializeObjectToXmlString<List<DataMaskResponse>>(DataMaskReponseList).ToXmlDocumentFragment().FirstChild.InnerXml); xmlDoc.LoadXml(m); XmlDocumentFragment frag = xmlDoc.CreateDocumentFragment(); //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<result/>"); //Create a document fragment. XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); //Set the contents of the document fragment. docFrag.InnerXml = "<ArrayOfDataMaskResponse><DataMaskResponse><name>AHA</name><value>1</value><Message>DRM/DPM tag inserted/updated successfully.</Message><Code>0</Code></DataMaskResponse><DataMaskResponse><name>Certegy Restricted</name><value>1</value><Message>DRM/DPM tag inserted/updated successfully.</Message><Code>0</Code></DataMaskResponse></ArrayOfDataMaskResponse>"; //Add the children of the document fragment to the //original document. doc.DocumentElement.AppendChild(docFrag); Console.WriteLine("Display the modified XML..."); Console.WriteLine(doc.OuterXml); Console.WriteLine(doc.OuterXml); /*SFTP downloadFTP = null; * * AddressInfo ftpInfo = new AddressInfo(); * * ftpInfo.Host = "mbsweb01.br.seisint.com"; * ftpInfo.Username = "******"; * ftpInfo.Password = "******"; * ftpInfo.Timeout = "300"; * ftpInfo.License = "8LQW-N7VA-VYDJ-C29F"; * ftpInfo.Blocking = "true"; * * FTPConfig.DownloadFTPAddress = ftpInfo; * * try * { * downloadFTP = FTPConnection.getFTPConnection(); * downloadFTP.Connect(); * * // Create folder if not already exists in IIS server to hold the files from the server for processing. * if (!Directory.Exists("..\\..\\Documents\\")) * { * Directory.CreateDirectory("..\\..\\Documents\\"); * } * * // Get file from remote server to local path. * downloadFTP.GetFile("..\\..\\Documents\\", "/u/mbs_uploads/accassi/201603/1457376627.csv"); * * downloadFTP.Disconnect(); * } * catch (Exception e) * { * throw new Exception(e.Message); * } */ /*GroupList.Add(new Group("SECURITY1", "1", "")); * GroupList.Add(new Group("SECURITY", "2", "1")); * GroupList.Add(new Group("INVWORKBENCH", "3", "1")); * GroupList.Add(new Group("COMPANY", "4", "2")); * GroupList.Add(new Group("MISCELLANEOUS", "5", "1")); * GroupList.Add(new Group("INVWORKBENCH", "6", "")); * GroupList.Add(new Group("INVWORKBENCH", "7", "")); * * string inputGroup = "SECURITY1"; * * ResultGroupList = new List<string>(); * * * string group_id = (from grp in GroupList * where grp.group_code == inputGroup * select grp.group_id).FirstOrDefault().ToString(); * * ResultGroupList.Add(group_id); * * List<string> ChildGroupList = (from grp in GroupList * where grp.parent_group_id == group_id * select grp.group_id).ToList(); * * foreach (string grp in ChildGroupList) * { * ResultGroupList.Add(grp); * } * * * GetChildGroups(ChildGroupList); * * * foreach (string grp in ResultGroupList) * { * Console.WriteLine(grp); * }*/ }