Best .net Method to create an XML Doc

前端 未结 11 647
爱一瞬间的悲伤
爱一瞬间的悲伤 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);
    
    0 讨论(0)
  • 2021-02-04 04:05

    I had to create following XML document having some part of it parametrized.

    <?xml version="1.0" encoding="utf-8"?>
    <wap-provisioningdoc>
      <characteristic type="BOOTSTRAP">
        <parm name="NAME" value="SYNCSETTINGS" />
      </characteristic>
      <characteristic type="APPLICATION">
        <parm name="APPID" value="w5" />
        <parm name="TO-NAPID" value="INTERNET" />
        <parm name="NAME" value="SYNCSETTINGS" />
        <parm name="ADDR" value="http://syncserver/sync" />
        <characteristic type="RESOURCE">
          <parm name="URI" value="pb" />
          <parm name="NAME" value="Contacts DB" />
          <parm name="AACCEPT" value="text/x-vcard" />
        </characteristic>
        <characteristic type="RESOURCE">
          <parm name="URI" value="cal" />
          <parm name="NAME" value="Calendar DB" />
          <parm name="AACCEPT" value="text/x-vcalendar" />
        </characteristic>
        <characteristic type="RESOURCE">
          <parm name="URI" value="notes" />
          <parm name="NAME" value="Notes DB" />
          <parm name="AACCEPT" value="text/plain" />
        </characteristic>
        <characteristic type="APPAUTH">
          <parm name="AAUTHNAME" value="username" />
          <parm name="AAUTHSECRET" value="password" />
        </characteristic>
      </characteristic>
    </wap-provisioningdoc>
    

    And here's my code that does this with single LINQ statement.

    Make a note that creating XML document above using LINQ and saving it to XML file preserves the XML document formatting and keeps line-breaks and carriage-returns that makes the document properly tabified.

    public string CreateOTAXmlFile(string Username, string Password)
        {
            var ota = new XDocument(
                        new XElement("wap-provisioningdoc",
                            new XElement("characteristic", new XAttribute("type", "BOOTSTRAP"),
                                new XElement("parm", new XAttribute("name", "NAME"), new XAttribute("value", "SYNCSETTINGS"))
                                        ),
                            new XElement("characteristic", new XAttribute("type", "APPLICATION"),
                                new XElement("parm", new XAttribute("name", "APPID"), new XAttribute("value", "w5")),
                                new XElement("parm", new XAttribute("name", "TO-NAPID"), new XAttribute("value", "INTERNET")),
                                new XElement("parm", new XAttribute("name", "NAME"), new XAttribute("value", "SYNCSETTINGS")),
                                new XElement("parm", new XAttribute("name", "ADDR"), new XAttribute("value", "http://syncserver/sync")),
                                new XElement("characteristic", new XAttribute("type", "RESOURCE"),
                                    new XElement("parm", new XAttribute("name", "URI"), new XAttribute("value", "pb")),
                                    new XElement("parm", new XAttribute("name", "NAME"), new XAttribute("value", "Contacts DB")),
                                    new XElement("parm", new XAttribute("name", "AACCEPT"), new XAttribute("value", "text/x-vcard"))
                                            ),
                                new XElement("characteristic", new XAttribute("type", "RESOURCE"),
                                    new XElement("parm", new XAttribute("name", "URI"), new XAttribute("value", "cal")),
                                    new XElement("parm", new XAttribute("name", "NAME"), new XAttribute("value", "Calendar DB")),
                                    new XElement("parm", new XAttribute("name", "AACCEPT"), new XAttribute("value", "text/x-vcalendar"))
                                            ),
                                new XElement("characteristic", new XAttribute("type", "RESOURCE"),
                                    new XElement("parm", new XAttribute("name", "URI"), new XAttribute("value", "notes")),
                                    new XElement("parm", new XAttribute("name", "NAME"), new XAttribute("value", "Notes DB")),
                                    new XElement("parm", new XAttribute("name", "AACCEPT"), new XAttribute("value", "text/plain"))
                                            ),
                                new XElement("characteristic", new XAttribute("type", "APPAUTH"),
                                    new XElement("parm", new XAttribute("name", "AAUTHNAME"), new XAttribute("value", Username)),
                                    new XElement("parm", new XAttribute("name", "AAUTHSECRET"), new XAttribute("value", Password))
                                            )
                                        )
                                    )
                                );
    
            ota.Save(Server.MapPath("~/OTA/") + Username + ".xml");
            return (ota.ToString());
    
        }
    
    0 讨论(0)
  • 2021-02-04 04:06

    There are a lot of good suggestions in this thread, but one that hasn't been mentioned: Defining an ADO DataSet and serializing/deserializing using the ReadXml and WriteXml methods. This can be a very simple and attractive solution. Your XML isn't in quite the right format, but it's close.

    0 讨论(0)
  • 2021-02-04 04:07

    I would suggest using the classes in System.Xml.Linq.dll which contain an XML DOM API that allows for easy build-up of XML structures due to the way the contructors are designed. Trying to create an XML structure using the System.Xml classes is very painful because you have to create them detached then separately add them into the document.

    Here's an example of XLinq vs. System.Xml to create a DOM from scratch. Your eyes will bleed when you see the System.Xml example.

    Here's a quick example of how you would use XLinq to build up part of your doc.

    var xml = new XElement("Orders",
        new XElement("Order",
            new XAttribute("OrderNumber", 12345),
            new XElement("ItemNumber", "01234567"),
            new XElement("QTY", 10),
            new XElement("Warehouse", "PA019")
        )
    );
    

    TIP Although it's a little unorthodox (though no worse than some of the language butchering that has become popular lately), I have on occasion used C#'s type aliasing feature to minimize the code even further:

    using XE = System.Xml.Linq.XElement;
    using XA = System.Xml.Linq.XAttribute;
    ...
    var xml = new XE("Orders",
        new XE("Order",
            new XA("OrderNumber", 12345),
            new XA("ItemNumber", "01234567"),
            new XA("QTY", 10),
            new XA("Warehouse", "PA019")
        )
    );
    
    0 讨论(0)
  • 2021-02-04 04:09

    If your use case is simple, nothing could possibly simpler and easier to use than XmlTextWriter. That said, one alternative would be to use an XmlDocument object to create and append all of your nodes. But I think it's easier to write and maintain code that uses XmlTextWriter if you're creating a document from scratch rather than manipulating one. Using XmlTextWriter should be very straightforward:

            StringBuilder output = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(output);
            writer.WriteProcessingInstruction("xml", "version=\"1.0\"");
            writer.WriteStartElement("Orders");
            //...start loop...
            writer.WriteStartElement("Order");
            writer.WriteAttributeString("OrderNumber", "12345");
            writer.WriteElementString("ItemNumber", "0123993587");
            writer.WriteElementString("QTY", "10");
            writer.WriteElementString("WareHouse", "PA019");
            writer.WriteEndElement();
            //...loop...
            writer.WriteEndElement();
            writer.Close();
    
    0 讨论(0)
提交回复
热议问题