Best .net Method to create an XML Doc

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

    What about this : create a class "Order" and one "Orders", and then serialize those out to XML - seems a lot easier to me than creating the XML bit by bit from hand....

    Since you say you're pulling the data off your ERP, you probably already have objects and classes for "Order" and so on - maybe it's sufficient to put a few [XmlElement] attributes on your classes and you're good to go!

    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;
    
    namespace XmlLinqTest
    {
        [Serializable]
        [XmlRoot(Namespace = "")]
        public class Orders
        {
            private List _orders = new List();
    
            /// 
            [XmlElement("Order")]
            public List OrderList
            {
                get { return _orders; }
            }
        }
    
        /// 
        [Serializable]
        public class Order
        {
            /// 
            [XmlElement]
            public string ItemNumber { get; set; }
    
            [XmlElement]
            public int QTY { get; set; }
    
            /// 
            [XmlElement]
            public string WareHouse { get; set; }
    
            /// 
            [XmlAttribute]
            public string OrderNumber { get; set; }
        }
    }
    

    and in your main app something like this:

    Orders orders = new Orders();
    
    Order work = new Order() { ItemNumber = "0123993587", OrderNumber = "12345", QTY = 10, WareHouse = "PA019" };
    orders.OrderList.Add(work);
    
    work = new Order() { ItemNumber = "0123993587", OrderNumber = "12346", QTY = 9, WareHouse = "PA019" };
    orders.OrderList.Add(work);
    
    work = new Order() { ItemNumber = "0123993587", OrderNumber = "12347", QTY = 8, WareHouse = "PA019" };
    orders.OrderList.Add(work);
    
    XmlSerializer ser = new XmlSerializer(typeof(Orders));
    
    using(StreamWriter wr = new StreamWriter(@"D:\testoutput.xml", false, Encoding.UTF8))
    {
        ser.Serialize(wr, orders);
    }
    

    Working with objects and then serializing them out to disk seems a lot easier to me than fiddling around with XDocument and other APIs.

提交回复
热议问题