读取和编写现有的xml文件c#3.0 / .net3.5

时间:2009-09-23 07:54:59

标签: c# xml .net-3.5

我有一个我想读的xml文件。我该怎么做?我不会在运行时加载整个xml文件

(XmlDocument _xd = XmlDocument.Load(path)) 

我想用读者来做,但我无法实现它。

同时我想用编写器向这个xml文件添加节点。这些如何与XDocument或c#3.5一起使用。

亲切的问候。

3 个答案:

答案 0 :(得分:2)

我认为this is useful

以下是一个例子:

using System;
using System.Xml;
namespace ReadXml1
{
    class Class1
    {
        static void Main(string[] args)
        {
            // Create an isntance of XmlTextReader and call Read method to read the file
            XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
            textReader.Read();
            // If the node has value
            while (textReader.Read())
            {
                // Move to fist element
                textReader.MoveToElement();
                Console.WriteLine("XmlTextReader Properties Test");
                Console.WriteLine("===================");
                // Read this element's properties and display them on console
                Console.WriteLine("Name:" + textReader.Name);
                Console.WriteLine("Base URI:" + textReader.BaseURI);
                Console.WriteLine("Local Name:" + textReader.LocalName);
                Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
                Console.WriteLine("Depth:" + textReader.Depth.ToString());
                Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
                Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
                Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
            }
        }
    }
}

以下是XMLWriters的示例:

使用System.Xml;

class Program
{
    class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;
        public Employee(int id, string firstName, string lastName, int salary)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
        }
        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
    }

    static void Main()
    {
        Employee[] employees = new Employee[4];
        employees[0] = new Employee(1, "David", "Smith", 10000);
        employees[1] = new Employee(3, "Mark", "Drinkwater", 30000);
        employees[2] = new Employee(4, "Norah", "Miller", 20000);
        employees[3] = new Employee(12, "Cecil", "Walker", 120000);

        using (XmlWriter writer = XmlWriter.Create("employees.xml"))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Employees");

            foreach (Employee employee in employees)
            {
                writer.WriteStartElement("Employee");

                writer.WriteElementString("ID", employee.Id.ToString());
                writer.WriteElementString("FirstName", employee.FirstName);
                writer.WriteElementString("LastName", employee.LastName);
                writer.WriteElementString("Salary", employee.Salary.ToString());

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }
}

答案 1 :(得分:1)

以下是使用XDocument加载xml文件,添加子节点并将其保存为使用的示例:

// Load XML file : 
XDocument xdoc = XDocument.Load(path);

// Parse XML : 
//XDocument xdoc = XDocument.Parse("<YourRootElement><ChildElement>Child 1</ChildElement></YourRootElement>");


// Add Child Node to loaded xml : 
xdoc.Element("YourRootElement").Add(
     new XElement("ChildElement", "Child 2"));

// Save XML to file : 
xdoc.Save(path);

编辑:使用XDocument.Parse method从内存加载XML。

答案 2 :(得分:0)

您是否也考虑过使用LINQ?像这样(只是假的,你必须在网上查找,但只是想知道)。

XDocument xmlDoc = //load or parse with XDocument.Load(..) or XDocument.Parse(...)

List<MyObject> myObj = (from myObject in xmlDoc.Descendants("myObjectTag")
                        select new MyObject
                        {
                            Name = (string)myObject.Attribute("name"),
                            ...
                        }
                        ).toList<MyObject>();

Voilà,这是我刚发现的一篇博客文章:* click *