C# XMLDocument

 

今天开发一个WPF模块需要本地化保存一些用户设置,鉴于数据量不大,用XML。 (要是再小的话可以用Resources 和 Settings)。

清晰简短教程移步:http://bdk82924.iteye.com/blog/564353

代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Kinect;

namespace KinectHost
{
    class SettingsXMLConfig
    {
        public SettingsXMLConfig(){

            createXML();
        }

        public void AddDoor(string name, string x, string y, string z, string threshold)
        {
            try
            {
                XmlElement doors = null;
                XmlElement theDoor = null, theName = null, theX = null, theY = null, theZ = null, theThreshold = null, root = null;

                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    doors = (XmlElement)root.SelectSingleNode("/XMLSettings/doors");

                    theDoor = xmlSetting.CreateElement("door");
                    theName = xmlSetting.CreateElement("name");
                    theName.InnerText = name;
                    theX = xmlSetting.CreateElement("x");
                    theX.InnerText = x;
                    theY = xmlSetting.CreateElement("y");
                    theY.InnerText = y;
                    theZ = xmlSetting.CreateElement("z");
                    theZ.InnerText = z;
                    theThreshold = xmlSetting.CreateElement("threshold");
                    theThreshold.InnerText = threshold;

                    theDoor.AppendChild(theName);
                    theDoor.AppendChild(theX);
                    theDoor.AppendChild(theY);
                    theDoor.AppendChild(theZ);
                    theDoor.AppendChild(theThreshold);

                    doors.AppendChild(theDoor);

                    xmlSetting.Save(filepath);
                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        public void RemoveDoor(string name)
        {
            XmlElement root = null, door = null;
            try
            {
                 string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    door = (XmlElement)root.SelectSingleNode("/XMLSettings/doors/door[name='" + name + "']");
                    door.ParentNode.RemoveChild(door);                 
                    
                    xmlSetting.Save(filepath);
                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        public List<CrossDoorDetector> SelectDoors(KinectSensor kinectSensor){
            XmlElement root = null, doors = null;
            List<CrossDoorDetector> crossDoorDetectorList = new List<CrossDoorDetector>();
            try
            {
                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    doors = (XmlElement)root.SelectSingleNode("/XMLSettings/doors");

                    string name = "";
                    float x = 0;
                    float y = 0;
                    float z = 0;
                    double threshold = 0;
                    if (doors.ChildNodes.Count > 0)
                    {
                        //XmlNode xn = doors.SelectSingleNode("door");
                        XmlNodeList xnl = doors.ChildNodes;
                        foreach (XmlNode xnf in xnl)
                        {
                            XmlElement xe = (XmlElement)xnf;
                            name = ((XmlElement)xe.SelectSingleNode("name")).InnerText;
                            float.TryParse(((XmlElement)xe.SelectSingleNode("x")).InnerText, out x);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("y")).InnerText, out y);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("z")).InnerText, out z);
                            double.TryParse(((XmlElement)xe.SelectSingleNode("threshold")).InnerText, out threshold);
                            crossDoorDetectorList.Add(new CrossDoorDetector(name, x, y, z, threshold, kinectSensor));
                        }
                        return crossDoorDetectorList;
                    }
                    else
                    {
                        return null;
                    }

                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                    return null;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
                return null;
            }
        }


        public void AddObject(string name, string x, string y, string z, string radius)
        {
            try
            {
                XmlElement doors = null;
                XmlElement theObject = null, theName = null, theX = null, theY = null, theZ = null, ObjectRadius = null, root = null;

                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    doors = (XmlElement)root.SelectSingleNode("/XMLSettings/objects");

                    theObject = xmlSetting.CreateElement("object");
                    theName = xmlSetting.CreateElement("name");
                    theName.InnerText = name;
                    theX = xmlSetting.CreateElement("x");
                    theX.InnerText = x;
                    theY = xmlSetting.CreateElement("y");
                    theY.InnerText = y;
                    theZ = xmlSetting.CreateElement("z");
                    theZ.InnerText = z;
                    ObjectRadius = xmlSetting.CreateElement("radius");
                    ObjectRadius.InnerText = radius;

                    theObject.AppendChild(theName);
                    theObject.AppendChild(theX);
                    theObject.AppendChild(theY);
                    theObject.AppendChild(theZ);
                    theObject.AppendChild(ObjectRadius);

                    doors.AppendChild(theObject);

                    xmlSetting.Save(filepath);
                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
        public List<ObjectPointing> SelectObjects()
        {
            XmlElement root = null, objects = null;
            List<ObjectPointing> objectPointingList = new List<ObjectPointing>();
            try
            {
                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    objects = (XmlElement)root.SelectSingleNode("/XMLSettings/objects");

                    string name = "";
                    float x = 0;
                    float y = 0;
                    float z = 0;
                    float radius = 0;
                    if (objects.ChildNodes.Count > 0)
                    {
                        //XmlNode xn = doors.SelectSingleNode("door");
                        XmlNodeList xnl = objects.ChildNodes;
                        foreach (XmlNode xnf in xnl)
                        {
                            XmlElement xe = (XmlElement)xnf;
                            name = ((XmlElement)xe.SelectSingleNode("name")).InnerText;
                            float.TryParse(((XmlElement)xe.SelectSingleNode("x")).InnerText, out x);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("y")).InnerText, out y);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("z")).InnerText, out z);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("radius")).InnerText, out radius);
                            objectPointingList.Add(new ObjectPointing(name, x, y, z, radius));
                        }
                        return objectPointingList;
                    }
                    else
                    {
                        return null;
                    }

                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                    return null;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
                return null;
            }
        }
        public void RemoveObject(string name)
        {
            XmlElement root = null, Object = null;
            try
            {
                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    Object = (XmlElement)root.SelectSingleNode("/XMLSettings/objects/object[name='" + name + "']");
                    Object.ParentNode.RemoveChild(Object);

                    xmlSetting.Save(filepath);
                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }


        public void AddLocation(string name, string x, string y, string z)
        {
            try
            {
                XmlElement doors = null;
                XmlElement theLocation = null, theName = null, theX = null, theY = null, theZ = null, root = null;

                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    doors = (XmlElement)root.SelectSingleNode("/XMLSettings/locations");

                    theLocation = xmlSetting.CreateElement("location");
                    theName = xmlSetting.CreateElement("name");
                    theName.InnerText = name;
                    theX = xmlSetting.CreateElement("x");
                    theX.InnerText = x;
                    theY = xmlSetting.CreateElement("y");
                    theY.InnerText = y;
                    theZ = xmlSetting.CreateElement("z");
                    theZ.InnerText = z;


                    theLocation.AppendChild(theName);
                    theLocation.AppendChild(theX);
                    theLocation.AppendChild(theY);
                    theLocation.AppendChild(theZ);

                    doors.AppendChild(theLocation);

                    xmlSetting.Save(filepath);
                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
        public List<LocationDetector> SelectLocations()
        {
            XmlElement root = null, objects = null;
            List<LocationDetector> locationDetectorList = new List<LocationDetector>();
            try
            {
                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    objects = (XmlElement)root.SelectSingleNode("/XMLSettings/locations");

                    string name = "";
                    float x = 0;
                    float y = 0;
                    float z = 0;
                    if (objects.ChildNodes.Count > 0)
                    {
                        //XmlNode xn = doors.SelectSingleNode("door");
                        XmlNodeList xnl = objects.ChildNodes;
                        foreach (XmlNode xnf in xnl)
                        {
                            XmlElement xe = (XmlElement)xnf;
                            name = ((XmlElement)xe.SelectSingleNode("name")).InnerText;
                            float.TryParse(((XmlElement)xe.SelectSingleNode("x")).InnerText, out x);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("y")).InnerText, out y);
                            float.TryParse(((XmlElement)xe.SelectSingleNode("z")).InnerText, out z);
                            locationDetectorList.Add(new LocationDetector(name, x, y, z));
                        }
                        return locationDetectorList;
                    }
                    else
                    {
                        return null;
                    }

                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                    return null;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
                return null;
            }
        }
        public void RemoveLocation(string name)
        {
            XmlElement root = null, location = null;
            try
            {
                string path = GetFolderPath();
                string filepath = Path.Combine(path, "XMLSettings.xml");
                if (File.Exists(filepath))
                {
                    XmlDocument xmlSetting = new XmlDocument();
                    xmlSetting.Load(filepath);

                    root = xmlSetting.DocumentElement;
                    location = (XmlElement)root.SelectSingleNode("/XMLSettings/locations/location[name='" + name + "']");
                    location.ParentNode.RemoveChild(location);

                    xmlSetting.Save(filepath);
                }
                else
                {
                    MessageBox.Show("XML Settings file doesn't extist!");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        private string GetFolderPath()
        {
            string folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XML");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            return folder;
        }

        private void createXML(){
            string path = GetFolderPath();
            string filepath = Path.Combine(path, "XMLSettings.xml");
            if (!File.Exists(filepath))
            {
                XmlDocument xmlSetting = new XmlDocument();
                XmlElement root = xmlSetting.CreateElement("XMLSettings");
                xmlSetting.AppendChild(root);

                XmlElement doors = xmlSetting.CreateElement("doors");
                XmlElement objects = xmlSetting.CreateElement("objects");
                XmlElement locations = xmlSetting.CreateElement("locations");
                root.AppendChild(doors);
                root.AppendChild(objects);
                root.AppendChild(locations);
                //string folder = Path.Combine(path, "XMLSettings.xml");
                xmlSetting.Save(filepath);
            }
         }

    }
}

XML结果:

<XMLSettings>
  <doors>
    <door>
      <name>Bedroom0</name>
      <x>165.5378</x>
      <y>208.586</y>
      <z>2.553757</z>
      <threshold>66.0010801284721</threshold>
    </door>
  </doors>
  <objects>
    <object>
      <name>Light</name>
      <x>-0.1636572</x>
      <y>0.762675</y>
      <z>1.719781</z>
      <radius>0.3</radius>
    </object>
  </objects>
  <locations>
    <location>
      <name>Desk</name>
      <x>0.02907251</x>
      <y>0.02481232</y>
      <z>2.383653</z>
    </location>
  </locations>
</XMLSettings>

  

posted @ 2014-10-24 20:42  bruceyo  阅读(1487)  评论(1编辑  收藏  举报