// Build the PhoneMetadataCollection from the input XML file. public static PhoneMetadataCollection buildPhoneMetadataCollection(String inputXmlFile, bool liteBuild) { // DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder builder = builderFactory.newDocumentBuilder(); var document = new XmlDocument(); // File xmlFile = new File(inputXmlFile); // Document document = builder.parse(xmlFile); document.Load(inputXmlFile); document.Normalize(); var territory = document.GetElementsByTagName("territory"); PhoneMetadataCollection.Builder metadataCollection = PhoneMetadataCollection.newBuilder(); int numOfTerritories = territory.Count; // TODO: Look for other uses of these constants and possibly pull them out into // a separate constants file. bool isShortNumberMetadata = inputXmlFile.Contains("ShortNumberMetadata"); bool isAlternateFormatsMetadata = inputXmlFile.Contains("PhoneNumberAlternateFormats"); for (int i = 0; i < numOfTerritories; i++) { XmlElement territoryXmlElement = (XmlElement)territory.Item(i); String regionCode = ""; // For the main metadata file this should always be set, but for other supplementary data // files the country calling code may be all that is needed. if (territoryXmlElement.HasAttribute("id")) { regionCode = territoryXmlElement.GetAttribute("id"); } PhoneMetadata metadata = loadCountryMetadata(regionCode, territoryXmlElement, liteBuild, isShortNumberMetadata, isAlternateFormatsMetadata); metadataCollection.addMetadata(metadata); } return(metadataCollection.build()); }
/// <summary> /// Signs xmldocument /// </summary> /// <param name="xmlDoc">Document to sign</param> /// <param name="tagName">Element to insert signature after</param> public void SignXmlDocument(XmlDocument xmlDoc, string tagName, X509Certificate2 x509Certificate2 = null) { if (x509Certificate2 != null) { this.x509Certificate2 = x509Certificate2; } xmlDoc.Normalize(); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = this.x509Certificate2.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); // Specify a canonicalization method. signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.KeyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(); keyInfoData.AddSubjectName(this.x509Certificate2.SubjectName.Name); keyInfoData.AddCertificate(this.x509Certificate2); signedXml.KeyInfo.AddClause(keyInfoData); signedXml.ComputeSignature(); XmlNodeList nodes = xmlDoc.DocumentElement.GetElementsByTagName(tagName); nodes[0].ParentNode.InsertAfter(xmlDoc.ImportNode(signedXml.GetXml(), true), nodes[0]); }
/// <summary> /// This method converts the SortedDictionary to XML. /// </summary> /// <returns>The XML.</returns> public XmlDocument GetXML() { XmlDocument xd = new XmlDocument(); xd.PreserveWhitespace = true; XmlElement parts = xd.CreateElement("parts"); xd.AppendChild(parts); foreach (KeyValuePair <int, Brick> kvp in dict) { XmlElement p = xd.CreateElement("part"); p.SetAttribute("itemNos", kvp.Value.GetItemNo().ToString()); p.SetAttribute("designID", kvp.Value.GetDesignID().ToString()); p.SetAttribute("materialID", kvp.Value.GetMaterialID().ToString()); p.SetAttribute("materialName", kvp.Value.GetMaterialName()); p.SetAttribute("materialCode", kvp.Value.GetMaterialCode()); p.SetAttribute("count", kvp.Value.GetCount().ToString()); p.SetAttribute("name", kvp.Value.GetName()); p.Normalize(); parts.AppendChild(p); } xd.Normalize(); xd.InsertBefore(xd.CreateXmlDeclaration("1.0", "UTF-8", "no"), xd.DocumentElement); return(xd); }
/// <summary> /// Permite agregar una nueva conexión. /// </summary> /// <param name="id">Identificador de la conexión.</param> /// <param name="servidor">Servidor de base de datos.</param> /// <param name="baseDeDatos">Nombre de la base de datos.</param> /// <param name="autentificacionWindows">Autentificación de Windows</param> /// <param name="usuario">Usuario.</param> /// <param name="contrasenia">Contraseña.</param> /// <returns>True en caso de éxito. False en caso contrario.</returns> private bool agregarNuevaConexion(string id, string servidor, string baseDeDatos, bool autentificacionWindows, string usuario, string contrasenia) { try { XmlDocument docVC = new XmlDocument(); docVC.LoadXml(System.IO.File.ReadAllText(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VCSoft", "VCfg.xml"))); XmlElement raiz = docVC.DocumentElement; XmlElement econexion = docVC.CreateElement("conexion"); econexion.SetAttribute("id", id); econexion.SetAttribute("servidor", servidor); econexion.SetAttribute("usuario", usuario); econexion.SetAttribute("contrasenia", contrasenia); econexion.SetAttribute("bd", baseDeDatos); econexion.SetAttribute("autWin", autentificacionWindows.ToString()); raiz.AppendChild(econexion).Normalize(); docVC.Normalize(); return(guardarXML(docVC)); } catch (Exception) { throw; } }
/// <summary> /// Prepares the source and target resource content for XML comparison /// </summary> /// <param name="resSvc">The resource service</param> /// <param name="sourceId">The source resource ID</param> /// <param name="targetId">The target resource ID</param> public static XmlComparisonSet PrepareForComparison(IResourceService resSvc, string sourceId, string targetId) { //Route both source and target XML content through //XmlDocument objects to ensure issues like whitespacing do //not throw us off var sourceFile = Path.GetTempFileName(); var targetFile = Path.GetTempFileName(); IResource source = resSvc.GetResource(sourceId); IResource target = resSvc.GetResource(targetId); var sourceDoc = new XmlDocument(); var targetDoc = new XmlDocument(); using (var sourceStream = ObjectFactory.Serialize(source)) using (var targetStream = ObjectFactory.Serialize(target)) { sourceDoc.Load(sourceStream); targetDoc.Load(targetStream); sourceDoc.Normalize(); targetDoc.Normalize(); using (var fs = File.OpenWrite(sourceFile)) using (var ft = File.OpenWrite(targetFile)) { sourceDoc.Save(fs); targetDoc.Save(ft); } return(new XmlComparisonSet( new TextFileDiffList(sourceFile, true), new TextFileDiffList(targetFile, true))); } }
public static void ReadCurrency() { try { // Load the data. XmlDocument doc = new XmlDocument(); doc.Load(URL); doc.Normalize(); // Process the resource nodes. XmlNodeList nList = doc.DocumentElement.GetElementsByTagName("Rate"); foreach (XmlNode node in nList) { string currency = node.Attributes.GetNamedItem("currency").Value; Double.TryParse(node.InnerText, out double value); int multiplier = -1; if (node.Attributes.GetNamedItem("multiplier") != null) { int.TryParse(node.Attributes.GetNamedItem("multiplier").Value, out multiplier); } ExchangeRates.Add(currency, new KeyValuePair <double, int>(value, multiplier)); } } catch (Exception ex) { Console.WriteLine(); #if DEBUG Debug.Print(ex.StackTrace); #endif } }
public static void EmptyDocument() { var xmlDocument = new XmlDocument(); xmlDocument.Normalize(); Assert.Equal(string.Empty, xmlDocument.OuterXml); }
/// <summary> /// Saving QuickMon monitor pack file /// </summary> /// <param name="configurationFile"></param> public void Save(string configurationFile) { string defaultViewerNotifier = ""; if (DefaultViewerNotifier != null) { defaultViewerNotifier = DefaultViewerNotifier.Name; } string outputXml = string.Format(Properties.Resources.MonitorPackXml, Name, Enabled, AgentsAssemblyPath, defaultViewerNotifier, RunCorrectiveScripts, GetConfigForCollectors(), GetConfigForNotifiers()); XmlDocument outputDoc = new XmlDocument(); outputDoc.LoadXml(outputXml); outputDoc.PreserveWhitespace = false; outputDoc.Normalize(); outputDoc.Save(configurationFile); MonitorPackPath = configurationFile; RaiseMonitorPackPathChanged(MonitorPackPath); if (Properties.Settings.Default.recentMonitorPacks == null) { Properties.Settings.Default.recentMonitorPacks = new System.Collections.Specialized.StringCollection(); } if (!Properties.Settings.Default.recentMonitorPacks.Contains(configurationFile)) { Properties.Settings.Default.recentMonitorPacks.Add(configurationFile); Properties.Settings.Default.Save(); } }
public static void Main(String[] args) { XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(args[0])); if (args[1] == "false") reader.ValidationType = ValidationType.None; else { reader.ValidationType = ValidationType.Schema; reader.ValidationEventHandler += new ValidationEventHandler (ValidationHandler); } XmlDocument doc = new XmlDocument(); doc.Load(reader); doc.Normalize(); XmlElement root = doc.DocumentElement; XmlNodeList titles = root.GetElementsByTagName("title"); for (int i=0; i < titles.Count; i++) { XmlNode title = titles[i]; XmlAttribute fullAt = title.Attributes["full"]; String full; if (fullAt == null) full = "true"; else full = fullAt.Value; XmlNode text = title.FirstChild; String result = (full=="false") ? "is not" : "is"; Console.WriteLine("{0} {1} the full title.", text.OuterXml, result); } }
/// <inheritdoc/> public override string BuildXmlTextDocument() { var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) { using (var xTarget = new XmlTextWriter(writer)) { var xDoc = new XmlDocument(); xDoc.LoadXml(element.OuterXml); xTarget.Formatting = Formatting.Indented; xTarget.Indentation = 2; xDoc.Normalize(); xDoc.PreserveWhitespace = true; xDoc.WriteContentTo(xTarget); xTarget.Flush(); xTarget.Close(); } } return(sb.ToString()); }
private XmlDocument GetLogData(string url, string revision, string username, string password) { Cache cache = HttpRuntime.Cache; string cacheKey = "LogData-" + revision + "-" + url; if (cache[cacheKey] != null) { //return (XmlDocument) cache[cacheKey]; } // svn log --xml -r [Revision] --non-interactive --limit [Limit] http://svn.website.com/svn/trunk Process proc = new Process(); proc.StartInfo.FileName = "svn"; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.Arguments = "log --xml " + GetRevisionArguments(revision, false) + GetAuthArguments(username, password) + " --non-interactive --limit " + FeedLimit + " " + url; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); proc.WaitForExit(WaitDelay); XmlDocument document = new XmlDocument(); document.Load(proc.StandardOutput); document.Normalize(); cache.Insert(cacheKey, document, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); return(document); }
/** * Save the contents type part. * * @param outStream * The output stream use to save the XML content of the content * types part. * @return <b>true</b> if the operation success, else <b>false</b>. */ public bool Save(Stream outStream) { XmlDocument xmlOutDoc = new XmlDocument(); XmlNamespaceManager xmlnm = new XmlNamespaceManager(xmlOutDoc.NameTable); xmlnm.AddNamespace("x", TYPES_NAMESPACE_URI); XmlElement typesElem = xmlOutDoc.CreateElement(TYPES_TAG_NAME, TYPES_NAMESPACE_URI); xmlOutDoc.AppendChild(typesElem); // Adding default types IEnumerator <KeyValuePair <string, string> > contentTypes = defaultContentType.GetEnumerator(); while (contentTypes.MoveNext()) { AppendDefaultType(xmlOutDoc, typesElem, contentTypes.Current); } // Adding specific types if any exist if (overrideContentType != null) { IEnumerator <KeyValuePair <PackagePartName, string> > overrideContentTypes = overrideContentType.GetEnumerator(); while (overrideContentTypes.MoveNext()) { AppendSpecificTypes(xmlOutDoc, typesElem, overrideContentTypes.Current); } } xmlOutDoc.Normalize(); // Save content in the specified output stream return(this.SaveImpl(xmlOutDoc, outStream)); }
/// <summary> /// 从配置文件里,获取Redis的密码 /// </summary> /// <returns></returns> public static void Get_Redis_Password() { try { string xmlPath = Path.Combine(Application.StartupPath, "Setting.xml"); //加载配置文件 XmlDocument xmlDocu = new XmlDocument(); xmlDocu.Normalize(); xmlDocu.Load(xmlPath); XmlNodeList xnlnode = xmlDocu.SelectSingleNode("HDLGraphicalSetting").ChildNodes; //遍历根节点下的子节点 foreach (XmlNode xn in xnlnode) { //图形监控系统子网号 if (xn.Name == "RedisPwd") { Redis_Password = xn.Attributes.GetNamedItem("value").Value; } } Export_Log_Info("Get the redis password success."); } catch (Exception ex) { Export_Log_Error("Get Redis Password Exception: " + ex.Message); } }
private void loadFiles() { _resxFiles = new List <ResxFile>(); foreach (var item in _gridEditableData.GetFileInformationsSorted()) { ZlpSimpleFileAccessProtector.Protect( delegate { using (var reader = XmlReader.Create(item.File.FullName)) { var doc = new XmlDocument(); doc.Load(reader); doc.Normalize(); _resxFiles.Add( new ResxFile { FileInformation = item, FilePath = item.File, Document = doc }); } }); } }
/// <summary> /// 从流中读取xml文档 /// </summary> /// <param name="fileStream"></param> /// <returns></returns> public static XmlNode GetXmlNode(FileStream fileStream) { XmlDocument tmp = new XmlDocument(); tmp.Normalize(); XmlNode tmpNode = null; try { tmp.Load(fileStream); if (tmp.ChildNodes.Count >= 2) { if (tmp.ChildNodes[0].Value.ToUpper() == "VERSION=\"1.0\" ENCODING=\"GB2312\"" || tmp.ChildNodes[0].Value.ToUpper() == "VERSION=\"1.0\" ENCODING=\"UTF-8\"") { tmpNode = tmp.ChildNodes[1]; } else { Error.Add("文档错误", "XML文档编码必须为<?xml version=\"1.0\" encoding=\"GB2312\" ?>"); } } } catch (Exception e) { Error.Add(e); } return(tmpNode); }
// Build the PhoneMetadataCollection from the input XML file. public static PhoneMetadataCollection BuildPhoneMetadataCollection(Stream input, bool liteBuild) { using (var reader = XmlReader.Create(input, new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore })) { var document = new XmlDocument(); document.Load(reader); document.Normalize(); var metadataCollection = new PhoneMetadataCollection.Builder(); foreach (XmlElement territory in document.GetElementsByTagName("territory")) { String regionCode = ""; // For the main metadata file this should always be set, but for other supplementary data // files the country calling code may be all that is needed. if (territory.HasAttribute("id")) { regionCode = territory.GetAttribute("id"); } PhoneMetadata metadata = LoadCountryMetadata(regionCode, territory, liteBuild); metadataCollection.AddMetadata(metadata); } return(metadataCollection.Build()); } }
// Helper method that outputs a DOM element from a XML string. private static XmlElement parseXmlString(String xmlString) { var document = new XmlDocument(); document.LoadXml(xmlString); document.Normalize(); return(document.DocumentElement); }
public static string Canonicalize(string xml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); doc.Normalize(); return(doc.DocumentElement.OuterXml); }
public void TestLocalToWebStyleFilter() { bool foundInlineStyles = false; bool foundNonXOfficeClasses = false; new LocalToWebStyleFilter(manager).Filter(ref initialXmlDoc); initialXmlDoc.Normalize(); expectedXmlDoc.Normalize(); XmlNodeList allNodes = initialXmlDoc.GetElementsByTagName("*"); foreach (XmlNode node in allNodes) { //searching for inline styles if (node.Attributes["style"] != null) { if (("" + node.Attributes["style"].Value).Length > 0) { foundInlineStyles = true; break; //no need to continue searching other problems } } //searching for non-XOffice CSS classes in nodes if (node.Attributes["class"] != null) { if (("" + node.Attributes["class"].Value).Length > 0) { if (node.Attributes["class"].Value.ToLower().IndexOf("xoffice") < 0) { foundNonXOfficeClasses = true; break; } } } } Assert.IsFalse(foundInlineStyles); Assert.IsFalse(foundNonXOfficeClasses); XmlNodeList totalStyleNodes = initialXmlDoc.GetElementsByTagName("style"); Assert.IsNotNull(totalStyleNodes); Assert.IsTrue(totalStyleNodes.Count == 1); XmlNode styleNode = initialXmlDoc.GetElementsByTagName("style")[0]; Assert.IsNotNull(styleNode); string cssContent = ExtractStyleContent(styleNode); int cssClassesCount = CountCSSClasses(cssContent); Assert.IsTrue(cssClassesCount == 5); //Assert.IsTrue(OptimizedCSSClasses(cssContent)); Assert.IsTrue(XmlDocComparator.AreIdentical(initialXmlDoc, expectedXmlDoc)); }
public static string Decrypt(string encryptedFile, string encryptionKey, out string appName) { appName = string.Empty; XmlDocument document = new XmlDocument(); string toDecrypt = string.Empty; FileInfo info = new FileInfo(encryptedFile); if (!info.Exists) { throw new Exception(string.Format("Could not find the specified input file: '{0}'", new object[] { encryptedFile })); } try { byte[] bytes; StreamReader reader = new StreamReader(encryptedFile); toDecrypt = reader.ReadToEnd(); reader.Dispose(); appName = Path.GetFileNameWithoutExtension(encryptedFile); try { bytes = Encoding.ASCII.GetBytes(Helper.SSO.Decrypt(toDecrypt, encryptionKey)); } catch (Exception exception1) { throw new Exception(string.Format("Failed to decrypt. {0}", exception1.Message), exception1); } MemoryStream inStream = new MemoryStream(bytes); try { document.Load(inStream); document.Normalize(); } catch (Exception exception2) { throw new Exception(string.Format("Failed to load xml. {0}", exception2.Message), exception2); } finally { inStream.Dispose(); } XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; // Save the document to a string and auto-indent the output. StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, settings); document.Save(writer); return(sb.ToString()); } catch (Exception) { throw; } }
private static XmlNode createDOM(XmlReader xmlFile) { XmlDocument doc = new XmlDocument(); doc.Load(xmlFile); doc.Normalize(); return(doc.DocumentElement); }
public static void EmptyWork() { 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>"; var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); xmlDocument.Normalize(); Assert.Equal(StripWhiteSpace(xml), StripWhiteSpace(xmlDocument.OuterXml)); }
private static void CleanAndNormalize(XmlDocument document) { XmlNodeList comments = document.SelectNodes("//comment()"); foreach (XmlNode comment in comments) { comment.ParentNode.RemoveChild(comment); } document.Normalize(); }
private string ToComparableXml(string xml) { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); xmlDocument.Normalize(); var stripWhiteSpace = new Regex(@">(\n|\s)*<"); return(stripWhiteSpace.Replace(xmlDocument.InnerXml, "><")); }
/// <summary> /// Constructor that accepts an XML string to work from /// </summary> /// <param name="ProgramXML"></param> /// <param name="FunctionSet"></param> public GPProgramReaderXML(String ProgramXML, IGPFunctionSet FunctionSet) { // // Save the function set m_FunctionSet = FunctionSet; // // Create a DOM document for parsing m_DocProgram = new XmlDocument(); m_DocProgram.LoadXml(ProgramXML); m_DocProgram.Normalize(); }
public static void NormalWork() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<doc><elem1>hello</elem1></doc>"); var text = xmlDocument.CreateTextNode("Test_test"); xmlDocument.DocumentElement.FirstChild.AppendChild(text); xmlDocument.Normalize(); Assert.Equal(1, xmlDocument.DocumentElement.FirstChild.ChildNodes.Count); }
/// <summary> /// Saving QuickMon monitor pack file /// </summary> /// <param name="configurationFile"></param> public void Save(string configurationFile) { XmlDocument outDoc = new XmlDocument(); outDoc.LoadXml(emptyConfig); XmlElement root = outDoc.DocumentElement; root.SetAttributeValue("version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); root.SetAttributeValue("name", Name); root.SetAttributeValue("typeName", TypeName); root.SetAttributeValue("enabled", Enabled); root.SetAttributeValue("runCorrectiveScripts", RunCorrectiveScripts); root.SetAttributeValue("stateHistorySize", CollectorStateHistorySize); root.SetAttributeValue("pollingFreqSecOverride", PollingFrequencyOverrideSec); root.SetAttributeValue("loggingEnabled", LoggingEnabled); #region security root.SetAttributeValue("usernameCacheMasterKey", UserNameCacheMasterKey); root.SetAttributeValue("usernameCacheFilePath", UserNameCacheFilePath); #endregion root.SelectSingleNode("configVars").InnerXml = GetConfigVarXml(); root.SelectSingleNode("collectorHosts").InnerXml = GetConfigForCollectors(); root.SelectSingleNode("notifierHosts").InnerXml = GetConfigForNotifiers(); #region Logging XmlNode loggingNode = root.SelectSingleNode("logging"); loggingNode.SetAttributeValue("loggingPath", LoggingPath); loggingNode.SetAttributeValue("loggingCollectorEvents", LoggingCollectorEvents); loggingNode.SetAttributeValue("loggingNotifierEvents", LoggingNotifierEvents); loggingNode.SetAttributeValue("loggingAlertsRaised", LoggingAlertsRaised); loggingNode.SetAttributeValue("loggingCorrectiveScriptRun", LoggingCorrectiveScriptRun); loggingNode.SetAttributeValue("loggingPollingOverridesTriggered", LoggingPollingOverridesTriggered); loggingNode.SetAttributeValue("loggingServiceWindowEvents", LoggingServiceWindowEvents); loggingNode.SetAttributeValue("loggingKeepLogFilesXDays", LoggingKeepLogFilesXDays); XmlNode loggingCollectorCategoriesNode = loggingNode.SelectSingleNode("collectorCategories"); foreach (string s in LoggingCollectorCategories) { XmlNode category = outDoc.CreateElement("category"); category.InnerText = s; loggingCollectorCategoriesNode.AppendChild(category); } #endregion outDoc.PreserveWhitespace = false; outDoc.Normalize(); outDoc.Save(configurationFile); MonitorPackPath = configurationFile; RaiseMonitorPackPathChanged(MonitorPackPath); WriteLogging("Monitor pack saved"); }
private void FailIfXmlNotEqual(TestCaseResult result, String ret, String orig) { XmlDocument xd_ret = new XmlDocument(); XmlDocument xd_orig = new XmlDocument(); xd_ret.LoadXml(ret); xd_orig.LoadXml(orig); xd_ret.Normalize(); xd_orig.Normalize(); result.FailIfNotEqual(xd_ret.DocumentElement.OuterXml, xd_orig.DocumentElement.OuterXml); }
public static XmlNode SaveXmlNodo() { XmlDocument xmldoc = new XmlDocument(); StringBuilder strNodo = new StringBuilder("<Categorias>"); foreach (Categoria categoria in categorias) { strNodo.Append(categoria.ToXml().OuterXml); } strNodo.Append("</Categorias>"); xmldoc.LoadXml(strNodo.ToString()); xmldoc.Normalize(); return(xmldoc.FirstChild); }
/// <summary> /// Pretty print XML data. /// </summary> /// <param name="xml">The string containing valid XML data.</param> /// <returns>The xml data in indented and justified form.</returns> private static string PrettyPrintXml(string xml) { var doc = new XmlDocument(); doc.LoadXml(xml); doc.Normalize(); TextWriter wr = new StringWriter(); doc.Save(wr); var str = wr.ToString(); return(str); }
/// <summary> /// Saving QuickMon monitor pack file /// </summary> /// <param name="configurationFile"></param> public void Save(string configurationFile) { XmlDocument outDoc = new XmlDocument(); outDoc.LoadXml(ToXml()); outDoc.PreserveWhitespace = false; outDoc.Normalize(); outDoc.Save(configurationFile); MonitorPackPath = configurationFile; RaiseMonitorPackPathChanged(MonitorPackPath); WriteLogging("Monitor pack saved"); }
public static void EmptyDocument() { var xmlDocument = new XmlDocument(); xmlDocument.Normalize(); Assert.Equal(String.Empty, xmlDocument.OuterXml); }
private XmlDocument GetLogData(string url, string revision, string username, string password) { Cache cache = HttpRuntime.Cache; string cacheKey = "LogData-" + revision + "-" + url; if (cache[cacheKey] != null) { //return (XmlDocument) cache[cacheKey]; } // svn log --xml -r [Revision] --non-interactive --limit [Limit] http://svn.website.com/svn/trunk Process proc = new Process(); proc.StartInfo.FileName = "svn"; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.Arguments = "log --xml " + GetRevisionArguments(revision, false) + GetAuthArguments(username, password) + " --non-interactive --limit " + FeedLimit + " " + url; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); proc.WaitForExit(WaitDelay); XmlDocument document = new XmlDocument(); document.Load(proc.StandardOutput); document.Normalize(); cache.Insert(cacheKey, document, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); return document; }
public static void Main(string[] args) { if (args.Length != 2) return; // Read in the output rules files XmlDocument stylesheet = new XmlDocument(); XmlElement stylesheet_root = stylesheet.CreateElement("xsl:stylesheet", "http://www.w3.org/1999/XSL/Transform"); stylesheet_root.SetAttribute("version", "1.0"); stylesheet.AppendChild(stylesheet_root); /*XmlElement outputnode = stylesheet.CreateElement("xsl:output", "http://www.w3.org/1999/XSL/Transform"); outputnode.SetAttribute("method", "text"); stylesheet_root.AppendChild(outputnode);*/ XmlElement basetemplate = stylesheet.CreateElement("xsl:template", "http://www.w3.org/1999/XSL/Transform"); basetemplate.SetAttribute("match", "*"); basetemplate.InnerXml = "[<xsl:value-of xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select=\"name()\"/>:" + "<xsl:for-each select='*' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" + "[<xsl:value-of select='name(.)'/>]" + "</xsl:for-each>]"; stylesheet_root.AppendChild(basetemplate); StreamReader csgen = new StreamReader("csgen.txt"); System.Text.RegularExpressions.Regex SubstParam = new System.Text.RegularExpressions.Regex(@"@([\w\*]+)(\[[^\]]+\])?"); string csgen_line; while ((csgen_line = csgen.ReadLine()) != null) { if (csgen_line == "" || csgen_line[0] == '#') { continue; } int sp = csgen_line.IndexOf(" "); if (sp == -1) { continue; } string rule = csgen_line.Substring(sp+1); int priority = -1; if (csgen_line.StartsWith("*")) priority = 10; if (csgen_line.StartsWith("!")) { priority = 20; csgen_line = csgen_line.Substring(1); } XmlElement template = stylesheet.CreateElement("xsl:template", "http://www.w3.org/1999/XSL/Transform"); template.SetAttribute("match", csgen_line.Substring(0, sp)); template.SetAttribute("xml:space", "preserve"); if (priority != -1) template.SetAttribute("priority", priority.ToString()); if (rule == "none") { template.InnerXml = "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='*'/>"; } else if (rule == "text") { template.InnerXml = "<xsl:value-of xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='@Text'/>"; } else { rule = rule.Replace("|", "\n"); if (!rule.EndsWith("\\")) rule += "\n"; else rule = rule.Substring(0, rule.Length-1); rule = rule.Replace("@@1", "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='*[position()>1]'/>"); rule = rule.Replace("@@", "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform'/>"); foreach (System.Text.RegularExpressions.Match match in SubstParam.Matches(rule)) { string type = match.Result("$1"); string sep = match.Result("$2"); if (sep != "") sep = sep.Substring(1, sep.Length-2); if (type == "text") { rule = rule.Replace(match.Value, "<xsl:value-of xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='@Text'/>"); } else { if (char.IsDigit(type[0])) type = "*[position()=" + type + "]"; if (sep == "") rule = rule.Replace(match.Value, "<xsl:apply-templates xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='" + type + "'/>"); else rule = rule.Replace(match.Value, "<xsl:for-each xmlns:xsl='http://www.w3.org/1999/XSL/Transform' select='" + type + "'>" + "<xsl:if test='not(position()=1)'>" + sep + "</xsl:if>" + "<xsl:apply-templates select='.'/>" + "</xsl:for-each>"); } } template.InnerXml = rule; } stylesheet_root.AppendChild(template); } CSharpAST left = GetAST(args[0]), right = GetAST(args[1]); StringWriter buffer = new StringWriter(); XmlTextWriter output = new XmlTextWriter(buffer); //output.Formatting = Formatting.Indented; StructuredDiff test = new XmlOutputStructuredDiff(output, null); test.AddInterface(typeof(ASTNode), new ASTNodeInterface()); test.Compare(left, right); output.Close(); XmlDocument diff = new XmlDocument(); diff.LoadXml(buffer.ToString()); XslTransform transform = new XslTransform(); transform.Load(stylesheet); XmlReader diffcontent = transform.Transform(diff, null); throw new Exception(diffcontent.BaseURI == null ? "null" : "not null"); XmlDocument diffdoc = new XmlDocument(); diffdoc.Load(diffcontent); diffdoc.Normalize(); WriteChildren(diffdoc.DocumentElement, 0, ' '); Console.WriteLine(); }