Best .net Method to create an XML Doc

前端 未结 11 649
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-04 03:33

I am trying to figure out what the best method is for writing an XML Document. Below is a simple example of what I am trying to create off of data I am pulling from our ERP syst

11条回答
  •  一向
    一向 (楼主)
    2021-02-04 04:02

    // 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);
    

提交回复
热议问题