How do I manipulate an XML document one parent element at a time?

前端 未结 2 1821
暗喜
暗喜 2021-01-24 09:46

I am trying to take an XML file containing multiple orders from an online shopping cart, parse it and output the values of each order as its own text file (not XML) using C# and

2条回答
  •  广开言路
    2021-01-24 10:24

    Chuck has a good approach. Sometimes, you don't want to retain the reference to the underlying xml data structure in the model object you are loading. In this case, I often use a pattern like this:

    public interface IXmlReadable
    {
        void Clear();
        void Read(XPathNavigator xmlNav);
    }
    
    public class ModelBase : IXmlReadable
    {
        public void Clear()
        {
            DoClear();
        }
    
        public void Read(XPathNavigator xmlNav)
        {
            DoRead(xmlNav);
        }
    
    
        protected virtual void DoClear()
        {
            throw new NotImplementedException();
        }
    
        protected virtual void DoRead(XPathNavigator xmlNav)
        {
            throw new NotImplementedException();
        }
    }
    

    Read can be overloaded to accept XmlDocument, XmlNode, XElement, etc.

    Now you can implement specific models.

    public sealed class Order : ModelBase
    {
        public Order() { }
    
        public string OrderNumber { get; private set; }
    
        protected override void DoClear()
        {
            OrderNumber = string.Empty;
        }
    
        protected override void DoRead(XPathNavigator xmlNav)
        {
            DoClear();
    
            XPathNavigator node;
    
            node = xmlNav.SelectSingleNode("OrderNumber");
    
            if (node != null)
                OrderNumber = node.InnerXml;
    
            // implement other properties here
        }
    
    }
    

    With the XPathDocument and XPathNavigator approach, you can then do something like this:

    XPathDocument xml = new XPathDocument(@"C:\onlinesales\neworders.xml");
    
    xmlNav = xml.CreateNavigator();
    
    XPathNodeIterator iterator = xmlNav.Select("Order");
    
    while (iterator.MoveNext())
    {
        Order order = new Order();
        order.Read(iterator.Current);
    
        // do something with the Order - add to list or process
    }
    

提交回复
热议问题