Best .net Method to create an XML Doc

前端 未结 11 687
爱一瞬间的悲伤
爱一瞬间的悲伤 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 03:53

    Josh's answer shows how easy it is to create a single element in LINQ to XML... it doesn't show how it's also hugely easy to create multiple elements. Suppose you have a List called orders... you can create the whole document like this:

    var xml = new XElement("Orders",
        orders.Select(order =>
            new XElement("Order",
                new XAttribute("OrderNumber", order.OrderNumber),
                new XElement("ItemNumber", order.ItemNumber),
                new XElement("QTY", order.Quantity),
                new XElement("Warehouse", order.Warehouse)
            )
        )
    );
    

    LINQ to XML makes constructing XML incredibly easy. It also has support for XML namespaces which is pretty easy too. For instance, if you wanted your elements to be in a particular namespace, you'd just need:

    XNamespace ns = "http://your/namespace/here";
    var xml = new XElement(ns + "Orders",
        orders.Select(order =>
            new XElement(ns + "Order",
    ... (rest of code as before)
    

    LINQ to XML is the best XML API I've worked with... it's great for querying too.

提交回复
热议问题