/// <summary> /// Returns the current AnimlDocument as its AnIML-XDocument representation. /// </summary> /// <returns>A XDocument representing the current AnimlDocument.</returns> public XDocument ToXDocument() { //// Create a new XDocument that follows the definition of the AnIML core schema in terms of declaration, namespace and root element. XDeclaration xDecl = new XDeclaration("1.0", "utf-8", "yes"); XDocument xDoc = new XDocument(xDecl); XElement animlElement = new XElement(NamespaceHelper.GetXName("AnIML")); animlElement.Add(new XAttribute("version", this.Version)); xDoc.Add(animlElement); //// Add all data elements if (this.SampleSet != null) { animlElement.Add(this.SampleSet.ToXElement()); } if (this.ExperimentStepSet != null) { animlElement.Add(this.ExperimentStepSet.ToXElement()); } if (this.AuditTrailEntrySet != null) { animlElement.Add(this.AuditTrailEntrySet.ToXElement()); } return(xDoc); }
public string ToKml() { var declaration = new XDeclaration("1.0", "utf-8", "yes"); var document = new XDocument(declaration); var kml = new XElement("kml"); kml.Add(new XAttribute("prefix", "http://www.opengis.net/kml/2.2")); var element = new XElement("Document"); foreach (var style in Symbols) { element.Add(style.ToKml()); } foreach (var feature in Features) { element.Add(feature.ToKml()); } kml.Add(element); document.Add(kml); var result = string.Concat(document.Declaration.ToString(), document.ToString()); result = result.Replace("prefix", "xmlns"); result = result.Replace(" standalone=\"yes\"", string.Empty); return(result); }
/// <summary>Private routine to build XDocument of URLs</summary> /// <param name="inputStream">Stream to read URL lines</param> /// <param name="urlChecker">Checker of read URL lines</param> /// <param name="logger">Wrong URL logger, may be null</param> /// <returns>XML document with URL's info</returns> private static XDocument BuildXDocumentRoutine(Stream inputStream, URLChecker urlChecker, TextWriter logger) { // Create XML document basement var declaration = new XDeclaration("1.0", "UTF-8", "yes"); var document = new XDocument(declaration, new XElement("urlAddresses")); // Read urls string url; var streamReader = new StreamReader(inputStream); while ((url = streamReader.ReadLine()) != null) { // Check url and print log if (urlChecker.CheckURL(url)) { var urlElement = BuildURLElement(url); document.Root.Add(urlElement); if (logger != null) { logger.WriteLine("[VALID]: " + url); } } else { if (logger != null) { logger.WriteLine("[INVALID]: " + url); } } } return(document); }
/// <summary> /// Constructor with xml declaration and content /// Use to create an MeiDocument from an existing parsed XDocument /// </summary> /// <param name="_xmldecl">Xml declaration</param> /// <param name="_root">Content root node</param> public MeiDocument(XDeclaration _xmldecl, MeiElement _root) : base(_xmldecl, _root) { if (_root.Attribute("meiversion") != null) { this.MeiVersion = _root.Attribute("meiversion").Value; } }
public void Pass_data(string basedirectory, string projectname, string projectdir) { this.basedir = basedirectory; this.projdir = projectdir; this.projname = projectname; this.filename = this.basedir + "GlobalMemberList.xml"; if (!File.Exists(this.filename))//this.basedir + "GlobalMemberList.xml")) { try { XDeclaration dec = new XDeclaration("1.0", "UTF-8", "yes"); XDocument doc = new XDocument(dec, new XElement("Global_member_list") ); doc.Save(this.filename);//basedir + "GlobalMemberList.xml"); } catch (Exception) { ShowMessage(3, null); } } EditModeSwitch(3); Populate_list(); }
public static XDocument Build(params XElement[] nodes) { XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", null); object[] xElement = new object[] { new XElement(SiteMapBuilder.Ns + "siteMap", nodes) }; return(new XDocument(xDeclaration, xElement)); }
private void xmlButton_Click(object sender, EventArgs e) { XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes"); XElement root_element = new XElement("Students"); foreach (Student s in F.students) { XElement info_element = new XElement("info"); info_element.Add(new XElement("RegNo", s.registrationNumber)); info_element.Add(new XElement("Name", s.studentName)); info_element.Add(new XElement("Class", s.classNumber)); info_element.Add(new XElement("Group", s.groupCode)); info_element.Add(new XElement("Subject1", s.subject1Score)); info_element.Add(new XElement("Subject2", s.subject2Score)); info_element.Add(new XElement("Subject3", s.subject3Score)); root_element.Add(info_element); } XDocument document = new XDocument(declaration, root_element); try { document.Save("C:\\Student_Files\\students.xml"); MessageBox.Show("Document has been saved to Student_Files in your C drive."); } catch { MessageBox.Show("Sorry, we were unable to save the file."); } }
/// <summary> /// Convert a document. /// </summary> /// <param name="document">The document to convert.</param> /// <returns>The number of errors found.</returns> public int ConvertDocument(XDocument document) { XDeclaration declaration = document.Declaration; // Convert the declaration. if (null != declaration) { if (!String.Equals("utf-8", declaration.Encoding, StringComparison.OrdinalIgnoreCase)) { if (this.OnError(ConverterTestType.DeclarationEncodingWrong, document.Root, "The XML declaration encoding is not properly set to 'utf-8'.")) { declaration.Encoding = "utf-8"; } } } else // missing declaration { if (this.OnError(ConverterTestType.DeclarationMissing, (XNode)null, "This file is missing an XML declaration on the first line.")) { document.Declaration = new XDeclaration("1.0", "utf-8", null); document.Root.AddBeforeSelf(new XText(XDocumentNewLine)); } } // Start converting the nodes at the top. this.ConvertNode(document.Root, 0); return(this.Errors); }
/// <summary> /// 创建默认的工作流配置 /// </summary> /// <param name="fullConfigFileName">配置文件</param> /// <param name="workflows">工作流定义集合</param> public void CreateWorkflows(string fullConfigFileName, List <WorkflowInfo> workflows) { XDocument doc = new XDocument(); //建立Xml的定义声明 XDeclaration declaration = new XDeclaration("1.0", "utf-8", null); doc.Declaration = declaration; //建立配置文件根节点 XElement element = new XElement(@"configuration"); doc.Add(element); //建立configSections节点 XElement sectionsElement = new XElement(@"configSections"); element.Add(sectionsElement); //LogicPath Section XElement logicPathSectionElement = CreateSectionXElement(@"LogicPath"); sectionsElement.Add(logicPathSectionElement); //LogicPath element XElement logicPathElement = CreateLogicPathXElement(workflows); element.Add(logicPathElement); foreach (WorkflowInfo workflow in workflows) { //Section sectionsElement.Add(CreateSectionXElement(workflow.Name)); //Element element.Add(CreateWorkflowXElement(workflow)); } doc.Save(fullConfigFileName); }
public static void TerritoriesSbc(ref XDocument document, List <SpawnGroup> territories) { XDeclaration declaration = new XDeclaration("1.0", "UTF-8", string.Empty); document.Declaration = declaration; XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; XNamespace xsd = "http://www.w3.org/2001/XMLSchema"; XElement root = new XElement("Definitions", new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName), new XAttribute(XNamespace.Xmlns + "xdi", xsd.NamespaceName) ); document.Add(root); XElement spawngroups = new XElement("Spawngroups"); root.Add(spawngroups); foreach (SpawnGroup sp in territories) { spawngroups.Add(NewSpawnGroupXml(sp)); } }
/// <summary>建立並初始化 <see cref="DailyXmlListener"/></summary> /// <param name="directory">欲存放記錄檔之目錄,如 @"D:\zongPanel\Logs"</param> public DailyXmlListener(string directory) { /* 擷取路徑 */ string dir = Path.GetDirectoryName(directory); if (!dir.EndsWith(@"\")) { dir += @"\"; } mLogDir = dir; /* 查看是否現有檔案需要載入 */ string file = EnsureFile(); if (File.Exists(file)) //有檔案,載入之 { mDoc = XDocument.Load(file); } else //沒檔案,建立之 { XDeclaration declare = new XDeclaration("1.0", "UTF-8", string.Empty); XElement root = new XElement("Logs"); mDoc = new XDocument(declare, root); } }
private void Init_CustomerOrdersDataGrid() { printHelper.SetGenerateXmlFile += (object collection) => { ObservableCollection <Order> customers = (ObservableCollection <Order>)collection; XDeclaration declaration = new XDeclaration("1.0", "utf-8", null); XDocument mainDocument = new XDocument(declaration, new XElement("Orders", customers.Select(o => new XElement("Order", new XAttribute("id", o.Id), new XElement("Comment", o.Comment) )))); return(mainDocument); }; xsltString = @"<?xml version='1.0'?> <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'> <xsl:template match='/'> <html> <head> <title> Objednávky </title> </head> <body> <xsl:for-each select='Orders/Order'> <xsl:value-of select='@id'/> <br /> <xsl:value-of select='Comment'/> <br /> <hr /> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet>"; }
/// <summary> /// Creates new XML document with specified declaration. /// </summary> public static XDoc New(XDocDeclaration declaration = XDocDeclaration.None) { XDeclaration xd; switch (declaration) { case XDocDeclaration.None: xd = null; break; case XDocDeclaration.UTF8: xd = new XDeclaration("1.0", "utf-8", null); break; case XDocDeclaration.UTF16: xd = new XDeclaration("1.0", "utf-16", null); break; case XDocDeclaration.UTF32: xd = new XDeclaration("1.0", "utf-32", null); break; default: throw new ArgumentException($"Unknown declaration type '{declaration}'"); } var doc = new XDocument(xd); return(new XDoc(doc)); }
static public void setfeedxml(Feed feed, string filename) { var xDocument0 = new XDocument(); XDeclaration xmlDeclaration = new XDeclaration("1.0", "utf-8", "yes"); xDocument0.Declaration = xmlDeclaration; XElement xeFeed = new XElement("Feed"); xeFeed.Add(new XElement("url", feed.url)); xeFeed.Add(new XElement("title", feed.title)); xeFeed.Add(new XElement("link", feed.link)); xeFeed.Add(new XElement("lastaclink", feed.lastaclink)); xeFeed.Add(new XElement("newfeedco", feed.newfeedco)); xeFeed.Add(new XElement("updatedate", feed.updateda)); foreach (var item in feed.content) { XElement xeFeedDate = new XElement("Feed_Data"); xeFeedDate.Add(new XElement("title", item.title)); xeFeedDate.Add(new XElement("link", item.link)); xeFeedDate.Add(new XElement("updatedate", item.updateda)); xeFeedDate.Add(new XElement("content", item.content)); xeFeed.Add(xeFeedDate); } xDocument0.Add(xeFeed); xDocument0.Save(filename); }
public string CreateSoapEnvelope(WfServiceOperationParameterCollection operationParams) { if (this._SvcOperationDef == null) { throw new ArgumentNullException("WfServiceOperationDefinition不能为空!"); } if (this._SvcOperationDef.OperationName.IsNullOrEmpty()) { throw new ArgumentNullException("OperationName不能为空!"); } XNamespace methodNS = this._SvcOperationDef.AddressDef.ServiceNS; XElement operationElement = new XElement(methodNS + this._SvcOperationDef.OperationName); foreach (WfServiceOperationParameter paramDef in operationParams) { XElement paraElement = new XElement(paramDef.Name); if (paramDef.Type == WfSvcOperationParameterType.RuntimeParameter) { Type dataType = paramDef.Value.GetType(); //mark 须从流程上下文取值,目前只是为了方便 PropertyInfo[] propsInfo = dataType.GetProperties(); //mark 用反射属性?还是用xml serialize? foreach (PropertyInfo item in propsInfo) { object propVal = item.GetValue(paramDef.Value, null); if (propVal == null) { continue; } paraElement.Add(new XElement(item.Name, propVal)); } } operationElement.Add(paraElement); } XElement envelopeElement = XElement.Parse(@"<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""><soap:Body></soap:Body></soap:Envelope>"); XElement bodyElement = (XElement)envelopeElement.FirstNode; bodyElement.Add(operationElement); XDeclaration xmlDeclare = new XDeclaration("1.0", "utf-8", ""); XDocument doc = new XDocument(xmlDeclare, envelopeElement); using (StringWriter writer = new StringWriter()) { doc.Save(writer); writer.Flush(); //mark string trashStr = @" xmlns="""""; return(writer.ToString().Replace("utf-16", "utf-8").Replace(trashStr, "")); } }
public File() { // Prepare the XML document XDeclaration declaration = new XDeclaration("1.0", "UTF-8", "yes"); _document = new XDocument(declaration); }
private String getXML() { XNamespace dte = XNamespace.Get("http://www.sat.gob.gt/dte/fel/0.1.0"); XNamespace xd = XNamespace.Get("http://www.w3.org/2000/09/xmldsig#"); //Encabezado del Documento XDeclaration declaracion = new XDeclaration("1.0", "utf-8", "no"); //GTDocumento XElement parameters = new XElement(dte + "GTAnulacionDocumento", new XAttribute(XNamespace.Xmlns + "ns", dte.NamespaceName), new XAttribute(XNamespace.Xmlns + "xd", xd.NamespaceName), new XAttribute("Version", "0.1")); //SAT XElement SAT = new XElement(dte + "SAT"); parameters.Add(SAT); // formando dte XElement DTE = new XElement(dte + "AnulacionDTE", new XAttribute("ID", "DatosCertificados")); SAT.Add(DTE); //datos de emision //datos generales XElement DatosGenerales = new XElement(dte + "DatosGenerales", new XAttribute("ID", "DatosAnulacion"), new XAttribute("NumeroDocumentoAAnular", this.anular.uuid), new XAttribute("NITEmisor", this.anular.NITEmisor), new XAttribute("IDReceptor", this.anular.IDReceptor), new XAttribute("FechaEmisionDocumentoAnular", this.anular.FechaEmisionDocumentoAnular), new XAttribute("FechaHoraAnulacion", this.anular.FechaHoraAnulacion), new XAttribute("MotivoAnulacion", this.anular.MotivoAnulacion)); DTE.Add(DatosGenerales); XDocument myXML = new XDocument(declaracion, parameters); String res = myXML.ToString(); try { v_rootxml = string.Format(@"{0}\{1}.xml", v_rootxml, fac_num.Trim()); if (!File.Exists(v_rootxml)) { myXML.Save(v_rootxml); } else { System.IO.File.Delete(v_rootxml); myXML.Save(v_rootxml); } } catch (Exception ex) { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + "docelec.txt"; System.IO.File.WriteAllText(path, ex.Message); } return(res); }
//4.3. XML static void GetCategoriesByProductsCountXML() { using (var db = new ProductsShopContext()) { var categories = db.Categories .Select(c => new { name = c.Name, productsCount = c.CategoryProducts.Count(), average = c.CategoryProducts.Average(p => p.Product.Price), total = c.CategoryProducts.Sum(p => p.Product.Price) }) .OrderByDescending(c => c.productsCount) .ToArray(); XDeclaration declaration = new XDeclaration("1.0", "utf-8", null); XDocument xDoc = new XDocument(declaration); var xmlDoc = new XDocument(new XElement("categories")); // това е root-a foreach (var c in categories) { xmlDoc.Root.Add(new XElement("catagory", new XAttribute("name", c.name), // значи май тук трябва да се провери за мин дълж!? new XElement("products-count", c.productsCount), new XElement("average-price", c.average), new XElement("total-revenue", c.total))); } string xmlString = xDoc.Declaration + Environment.NewLine + xmlDoc; //string xmlString = xmlDoc.ToString(); File.WriteAllText("ExportedFiles/GetCategoriesByProductsCountXML.xml", xmlString); } }
/// <summary> /// This method gets parsing output for given input and then creates and returns specific XML formatted text. /// </summary> /// <param name="input">Input text to be parsed and formatted in specific XML output.</param> /// <returns>It returns a string/text output in a specific XML format.</returns> public string Convert(string input) { List <Sentence> inputSentences = Parse(input); StringBuilder xmlOutput = new StringBuilder(); try { var sentenceElements = inputSentences.Select(sentence => { var wordElements = sentence.Words.Select(word => new XElement("word", word)); return(new XElement("sentence", wordElements)); }); var rootElement = new XElement("text", sentenceElements); var xmlDeclaration = new XDeclaration(Constants.XML_VERSION, Constants.XML_ENCODING, Constants.XML_IS_STANDALONE); XDocument xDoc = new XDocument(xmlDeclaration, rootElement); using (StringWriter writer = new StringWriter(xmlOutput)) { xDoc.Save(writer); } } catch (Exception ex) { logger.Log("Some error occured in XmlConverter.Convert method. Error details are- " + ex.Message); } return(xmlOutput.ToString()); }
//4.1. XML static void GetProductsInRangeXML() { using (var db = new ProductsShopContext()) { var products = db.Products .Where(p => p.Price >= 1000 && p.Price <= 2000 && p.BuyerId != null) .Select(b => new { name = b.Name, price = b.Price, buyer = $"{b.Buyer.FirstName} {b.Buyer.LastName}" }).OrderBy(p => p.price) .ToArray(); XDeclaration declaration = new XDeclaration("1.0", "utf-8", null); XDocument xDoc = new XDocument(declaration); var xmlDoc = new XDocument(new XElement("products")); // това е root-a foreach (var product in products) { xmlDoc.Root.Add(new XElement("product", new XAttribute("name", product.name), new XAttribute("price", product.price), new XAttribute("buyer", product.buyer))); } string xmlString = xDoc.Declaration + Environment.NewLine + xmlDoc; //string xmlString = xmlDoc.ToString(); File.WriteAllText("ExportedFiles/GetProductsInRangeXML.xml", xmlString); //xmlDoc.Save("ExportedFiles/GetProductsInRangeXML.xml"); // var.2 for Save } }
/*========================================================================================================================== | GET: /SITEMAP \-------------------------------------------------------------------------------------------------------------------------*/ /// <summary> /// Provides the Sitemap.org sitemap for the site. /// </summary> /// <param name="indent">Optionally enables indentation of XML elements in output for human readability.</param> /// <param name="includeMetadata">Optionally enables extended metadata associated with each topic.</param> /// <returns>A Sitemap.org sitemap.</returns> public virtual ActionResult Index(bool indent = false, bool includeMetadata = false) { /*------------------------------------------------------------------------------------------------------------------------ | Ensure topics are loaded \-----------------------------------------------------------------------------------------------------------------------*/ var rootTopic = _topicRepository.Load(); Contract.Assume( rootTopic, $"The topic graph could not be successfully loaded from the {nameof(ITopicRepository)} instance. The " + $"{nameof(SitemapController)} is unable to establish a local copy to work off of." ); /*------------------------------------------------------------------------------------------------------------------------ | Establish sitemap \-----------------------------------------------------------------------------------------------------------------------*/ var declaration = new XDeclaration("1.0", "utf-8", "no"); var sitemap = GenerateSitemap(rootTopic, includeMetadata); var settings = indent? SaveOptions.None : SaveOptions.DisableFormatting; /*------------------------------------------------------------------------------------------------------------------------ | Return the homepage view \-----------------------------------------------------------------------------------------------------------------------*/ return(Content(declaration.ToString() + sitemap.ToString(settings), "text/xml")); }
/// <summary> /// Imports the type of the content. /// </summary> /// <param name="contentTypeInfo">The content type info.</param> public static void ImportContentType(ContentTypeInfo contentTypeInfo) { if (contentTypeInfo != null) { //Create the encoding definition XDeclaration declaration = new XDeclaration("1.0", Encoding.UTF8.WebName, null); XNamespace sharepointToolsNamespace = @"http://schemas.microsoft.com/VisualStudio/2010/SharePointTools/SharePointProjectItemModel"; XNamespace sharepointNamespace = @"http://schemas.microsoft.com/sharepoint/"; XElement elementsFileContents = XElement.Parse(BuildElements(contentTypeInfo, declaration, sharepointNamespace)); EnvDTE.Project activeProject = DTEManager.ActiveProject; if (activeProject != null) { ISharePointProjectService projectService = DTEManager.ProjectService; ISharePointProject activeSharePointProject = DTEManager.ActiveSharePointProject; if (activeSharePointProject != null) { ISharePointProjectItem contentTypeProjectItem = activeSharePointProject.ProjectItems.Add(contentTypeInfo.Name, "Microsoft.VisualStudio.SharePoint.ContentType"); System.IO.File.WriteAllText(Path.Combine(contentTypeProjectItem.FullPath, "Elements.xml"), elementsFileContents.ToString().Replace("xmlns=\"\"", String.Empty)); ISharePointProjectItemFile elementsXml = contentTypeProjectItem.Files.AddFromFile("Elements.xml"); elementsXml.DeploymentType = DeploymentType.ElementManifest; elementsXml.DeploymentPath = String.Format(@"{0}\", contentTypeInfo.Name); contentTypeProjectItem.DefaultFile = elementsXml; } } } }
/// <summary> /// Creates an empty user.config file...looks like the one MS creates. /// This could be overkill a simple key/value pairing would probably do. /// </summary> private void CreateEmptyConfig() { var doc = new XDocument(); var declaration = new XDeclaration("1.0", "utf-8", "true"); var config = new XElement(CONFIG); var userSettings = new XElement(USER_SETTINGS); var group = new XElement(typeof(Properties.Settings).FullName); userSettings.Add(group); config.Add(userSettings); doc.Add(config); doc.Declaration = declaration; string dirName = Path.GetDirectoryName(UserConfigPath); try { if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } doc.Save(UserConfigPath); } catch (Exception e) { Log.WriteLine(LogLevel.Error, e.Message); } }
static void Main(string[] args) { XDeclaration myDeclaration = new XDeclaration("1.0", "utf-8", "yes"); XDocumentType myDocType = new XDocumentType("FruitList", null, null, null); // create XElements XElement myNameElement = new XElement("Name", "Orange"); XElement mySizeElement = new XElement("Size", "Large"); // create my root element XElement myRootElement = new XElement("Fruit", myNameElement, mySizeElement); // create the XML document XDocument myDoc = new XDocument( myDeclaration, myDocType, myRootElement); // print out the XElement object Console.WriteLine(myDoc); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
private static void ExportXmlToFolder <TEntity>(TEntity entityType, string pathToExport) { XDeclaration declaration = new XDeclaration("1.0", "utf-8", null); XDocument xDoc = new XDocument(declaration); // Add data: xDoc.Add(new XElement("categories")); string result = xDoc.Declaration + Environment.NewLine + xDoc; }
/// <summary> /// Gets the <see cref="System.Xml.Linq.XDeclaration"/>. /// </summary> /// <param name="encoding">The encoding (<see cref="XEncoding.Utf08"/> by default).</param> /// <param name="isStandAlone">When <c>true</c> document is stand-alone (<c>true</c> by default).</param> public static XDeclaration GetXDeclaration(string encoding, bool isStandAlone) { var declaration = new XDeclaration("1.0", encoding, (isStandAlone ? "yes" : "no")); return(declaration); }
protected override async Task <string> CreateStructureAsync(IEnumerable <Sentence> sentences) { var header = new XDeclaration(version: "1.0", encoding: "utf-8", standalone: "yes"); var doc = new XDocument( // xml -> xsd, xmlsoap -> wsdl, xslt (transformata) new XElement("text", from sentence in sentences select new XElement("sentence", from word in sentence.Words select new XElement("word", word)//SecurityElement.Escape(word).Replace("\'", "'")) ))); var text = doc.ToString() .Replace("&", "&amp;") .Replace("<", "&lt;") .Replace(">", "&gt;") .Replace("\'", "&apos;") .Replace("\"", "&quot;"); var xml = new StringWriterUtf8(); await xml.WriteAsync(header.ToString() + "\r\n" + text); var ooo = xml.ToString(); return(await Task.FromResult(ooo)); }
private static string XmlProductsInRande() { using (var db = new ProductShopContext()) { var products = db.Products.Where(p => (p.Price >= 1000 && p.Price <= 2000) && p.Buyer != null) .Select(p => new { Name = p.Name, Price = p.Price, Buyer = $"{p.Buyer.FirstName ?? ""} {p.Buyer.LastName}" }) .OrderBy(p => p.Price).ToArray(); XDeclaration declaration = new XDeclaration("1.0", "utf-8", null); var productDoc = new XDocument(declaration); productDoc.Add(new XElement("products")); foreach (var product in products) { productDoc.Element("products") .Add(new XElement("product", new XAttribute("name", product.Name), new XAttribute("price", product.Price), new XAttribute("buyer", product.Buyer))); } string result = productDoc.Declaration + Environment.NewLine + productDoc; File.WriteAllText("products-in-range.xml", result); return("Successfully created file 'products-in-range.xml'"); } }
public static byte[] Serialize(IEnumerable <Rule> powershellRules) { byte[] result; using (MemoryStream memoryStream = new MemoryStream()) { XDeclaration declaration = new XDeclaration("1.0", "utf-16", "yes"); object[] array = new object[1]; object[] array2 = array; int num = 0; XName name = XName.Get("rules"); object[] array3 = new object[2]; array3[0] = new XAttribute("name", "TransportVersioned"); array3[1] = from rule in powershellRules select new XElement("rule", new object[] { new XAttribute(XName.Get("name"), rule.Name), new XAttribute(XName.Get("id"), rule.ImmutableId), new XAttribute(XName.Get("format"), "cmdlet"), new XElement(XName.Get("version"), new object[] { new XAttribute(XName.Get("requiredMinVersion"), "15.0.3.0"), new XElement(XName.Get("commandBlock"), new XCData(rule.ToCmdlet())) }) }); array2[num] = new XElement(name, array3); XDocument xdocument = new XDocument(declaration, array); xdocument.Save(memoryStream); result = memoryStream.ToArray(); } return(result); }
protected void btnCreate2_OnClick(object sender, EventArgs e) { var filePath = Server.MapPath("books_2.xml"); try { var book = new XElement("book"); var bookAttr = new XAttribute("genre", "philosophy"); book.Add(bookAttr); book.Add(new XElement("title", "Critique of Pure Reason")); var author = new XElement("author"); author.Add(new XElement("first-name", "Immuanuel")); author.Add(new XElement("last-name", "Kant")); book.Add(author); book.Add(new XElement("price", "9.99")); var bookstore = new XElement("bookstore"); bookstore.Add(book); var declaration = new XDeclaration("1.0", "UTF-8", "yes"); var xdoc = new XDocument(declaration, bookstore); xdoc.Save(filePath); Response.Write("文档创建成功"); } catch (Exception ex) { throw new Exception(ex.Message); } }