Best .net Method to create an XML Doc

前端 未结 11 643
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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")
        )
    );
    

提交回复
热议问题