Creating a XML Document from scratch without using a file in C#
2010-07-08 09:45
645 查看
Creating
a XML Document from scratch without using a file in C#
April 4, 2007
One thing that’s annoying is that
majority of the XML example assumes that you are loading an XML document
from a file, so here’s a simple code example for generating it entirely
in memory.
// Create Books
// Note that to set the text inside the element,
// you use .InnerText instead of .Value (which will throw an exception).
// You use SetAttribute to set attribute
XmlElement book = doc.CreateElement("Book");
book.SetAttribute("BookType", "Hardcover");
XmlElement title = doc.CreateElement("Title");
title.InnerText = "Door Number Three";
XmlElement author = doc.CreateElement("Author");
author.InnerText = "O'Leary, Patrick";
book.AppendChild(title);
book.AppendChild(author);
root.AppendChild(book);
book = doc.CreateElement("Book");
book.SetAttribute("BookType", "Paperback");
title = doc.CreateElement("Title");
title.InnerText = "Lord of Light";
author = doc.CreateElement("Author");
author.InnerText = "Zelanzy, Roger";
book.AppendChild(title);
book.AppendChild(author);
root.AppendChild(book);
string xmlOutput = doc.OuterXml;
The same code but using an XMLWriter to a memory stream.
// Write the root node
xw.WriteStartElement("Library");
// Write the books and the book elements
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Hardback");
xw.WriteEndAttribute();
xw.WriteStartElement("Title");
xw.WriteString("Door Number Three");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("O'Leary, Patrick");
xw.WriteEndElement();
xw.WriteEndElement();
// Write another book
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Paperback");
xw.WriteEndAttribute();
xw.WriteStartElement("Title");
xw.WriteString("Lord of Light");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("Zelanzy, Roger");
xw.WriteEndElement();
xw.WriteEndElement();
// Close the document
xw.WriteEndDocument();
// Flush the write
xw.Flush();
Byte[] buffer = new Byte[ms.Length];
buffer = ms.ToArray();
string xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);
-------------------------------------------------------------------------------------------------------------------------------
Create a New XML File Using XmlDocument
Here's the XML File:
[/code]
Here's the code:
[/code]
a XML Document from scratch without using a file in C#
April 4, 2007
One thing that’s annoying is that
majority of the XML example assumes that you are loading an XML document
from a file, so here’s a simple code example for generating it entirely
in memory.
// Create the xml document containe XmlDocument doc = new XmlDocument();
// Create the XML Declaration, and append it to XML document XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null); doc.AppendChild(dec);
// Create the root element XmlElement root = doc.CreateElement("Library"); doc.AppendChild(root);
// Create Books
// Note that to set the text inside the element,
// you use .InnerText instead of .Value (which will throw an exception).
// You use SetAttribute to set attribute
XmlElement book = doc.CreateElement("Book");
book.SetAttribute("BookType", "Hardcover");
XmlElement title = doc.CreateElement("Title");
title.InnerText = "Door Number Three";
XmlElement author = doc.CreateElement("Author");
author.InnerText = "O'Leary, Patrick";
book.AppendChild(title);
book.AppendChild(author);
root.AppendChild(book);
book = doc.CreateElement("Book");
book.SetAttribute("BookType", "Paperback");
title = doc.CreateElement("Title");
title.InnerText = "Lord of Light";
author = doc.CreateElement("Author");
author.InnerText = "Zelanzy, Roger";
book.AppendChild(title);
book.AppendChild(author);
root.AppendChild(book);
string xmlOutput = doc.OuterXml;
The same code but using an XMLWriter to a memory stream.
XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Indent = true; MemoryStream ms = new MemoryStream(); XmlWriter xw = XmlWriter.Create(ms, wSettings);
// Write Declaration xw.WriteStartDocument();
// Write the root node
xw.WriteStartElement("Library");
// Write the books and the book elements
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Hardback");
xw.WriteEndAttribute();
xw.WriteStartElement("Title");
xw.WriteString("Door Number Three");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("O'Leary, Patrick");
xw.WriteEndElement();
xw.WriteEndElement();
// Write another book
xw.WriteStartElement("Book");
xw.WriteStartAttribute("BookType");
xw.WriteString("Paperback");
xw.WriteEndAttribute();
xw.WriteStartElement("Title");
xw.WriteString("Lord of Light");
xw.WriteEndElement();
xw.WriteStartElement("Author");
xw.WriteString("Zelanzy, Roger");
xw.WriteEndElement();
xw.WriteEndElement();
// Close the document
xw.WriteEndDocument();
// Flush the write
xw.Flush();
Byte[] buffer = new Byte[ms.Length];
buffer = ms.ToArray();
string xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);
-------------------------------------------------------------------------------------------------------------------------------
Create a New XML File Using XmlDocument
Here's the XML File:
<?xml version="1.0" encoding="utf-8"?> <CategoryList> <Category ID="01"> <MainCategory>XML</MainCategory> <Description>This is a list my XML articles.</Description> <Active>true</Active> </Category> </CategoryList>
[/code]
Here's the code:
<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Xml" %> <%@ Page Language="C#" Debug="true" %> <script runat="server"> void Page_Load(object sender, System.EventArgs e){ if(!Page.IsPostBack){ XmlDocument xmlDoc = new XmlDocument(); // Write down the XML declaration XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null); // Create the root element XmlElement rootNode = xmlDoc.CreateElement("CategoryList"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); xmlDoc.AppendChild(rootNode); // Create a new <Category> element and add it to the root node XmlElement parentNode = xmlDoc.CreateElement("Category"); // Set attribute name and value! parentNode.SetAttribute("ID", "01"); xmlDoc.DocumentElement.PrependChild(parentNode); // Create the required nodes XmlElement mainNode = xmlDoc.CreateElement("MainCategory"); XmlElement descNode = xmlDoc.CreateElement("Description"); XmlElement activeNode = xmlDoc.CreateElement("Active"); // retrieve the text XmlText categoryText= xmlDoc.CreateTextNode("XML"); XmlText descText = xmlDoc.CreateTextNode("This is a list my XML articles."); XmlText activeText = xmlDoc.CreateTextNode("true"); // append the nodes to the parentNode without the value parentNode.AppendChild(mainNode); parentNode.AppendChild(descNode); parentNode.AppendChild(activeNode); // save the value of the fields into the nodes mainNode.AppendChild(categoryText); descNode.AppendChild(descText); activeNode.AppendChild(activeText); // Save to the XML file xmlDoc.Save( Server.MapPath("categories.xml")); Response.Write("XML file created"); } } </script>
[/code]
相关文章推荐
- Serialization from an Object to XML Document in C#
- Using DocumentFormat.OpenXml to generate a new excel file in terms of temp excel file
- Creating a new Microsoft Word document from a template using OpenXml
- How to create an XTR file from XML in Delphi XE4 using XML Mapper?(delphi中如何通过xmlmapper创建xtr文件)
- Serialization in C# without using file system
- Using Databases with Python -Musical Track Database (produce database from XML file)
- Serialize and deserialize objects as Xml using generic types in C# 2.0
- org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource
- Using C# Generics read & update XML file .
- How To Generate An XML File As A Target Datastore Using ODI In An Integration Interface ? [ID 454268
- Using distributed transactions in .Net 1.x without deriving from ServicedComponent
- XML文件要有根标签(Extra content at the end of the document in file 错误)
- Generate the java class from XML Schema file using JAXB
- org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 2 in XML document from c
- How to upload a file via a HTTP multipart request in Java without using any external libraries
- [存底]使用C#压缩/解压缩7-zip文件 zip/Unzip file using 7-zip in C#
- (OK) Creating manually one VMs from an existing VDI file in CLI (VBoxManage) in Fedora 23
- Generate the java class from XML Schema file using JAXB
- Creating a Web Control with an Expandable Property in the Designer by Using C#.
- org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from U