且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#在XML文件中添加新记录

更新时间:2023-11-23 22:30:04

虽然主要使用 Xdocument ,但我认为在你的情况下 Xelement 更容易使用,以下是一些示例: XElement类概述 [ ^ ]



Although Xdocument is mostly used, I think in your case Xelement is easier to use, here are some examples: XElement Class Overview[^]

XElement contacts =
new XElement("Contacts",
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"), 
        new XElement("Phone", "206-555-0144"),
        new XElement("Address",
            new XElement("Street1", "123 Main St"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    )
);







// This is an WPF example !
private XElement xmlSource;




// Set the datagrid source to XML file.
this.xmlSource = XElement.Load(this.fileName);
this.DataGrid1.DataContext = this.xmlSource;




this.xmlSource.Save(this.fileName);


引用:

我混淆了从哪里开始。

I confuse where to start.

从Google开始并搜索XLM读/写库。

随意阅读文档并按照教程进行操作。

抱歉没时间搜索你。

Start with Google and search an XLM reader/writer library.
Feel free do read documentation and follow tutorials too.
Sorry no time to do search for you.


实现这一点的方法很少:

1)使用System.Xml.Linq类: XDocument [ ^ ] + XElement [ ^ ] + XAttribute [ ^ ]:

There's few ways to achieve that:
1) using System.Xml.Linq classes: XDocument[^] + XElement[^] + XAttribute[^]:
string xcontent = @"<Project>
  <ProjectDetail id='0'>
    <title>Batman vs Superman</title>
    <platform>TV OS</platform>
    <code>5504</code>
    <dbname>BVSM</dbname>
  </ProjectDetail>
</Project>";

//just for example
XDocument xdoc = XDocument.Parse(xcontent);
//you should use:
//XDocument xdoc = XDocument.Load("FullFileName.xml");

XElement xele = new XElement("ProjectDetail", new XAttribute("id", 1),
	new XElement("title", "Cartman and Stan"),
	new XElement("platform", "TV OS"), 
	new XElement("code", 1048),
	new XElement("dbname", "CAS"));

xdoc.Root.Add(xele);
xdoc.Save("FullFileName.xml");





2)使用System.Xml类: XmlReader [ ^ ] + XmlWriter [ ^ ]



3)使用Xml序列化和反序列化

XML序列化简介 [ ^ ]

XML序列化示例 [ ^ ]

XML序列化和反序列化:第1部分 [ ^ ]

XML序列化和反序列化:第2部分 [ ^ ]

自定义类集合序列化和反序列化的完整示例 [ ^ ]



试试!



2) using System.Xml classes: XmlReader[^] + XmlWriter[^]

3) using Xml Serialization and Deserialization
Introducing XML Serialization[^]
Examples of XML Serialization[^]
XML Serialization and Deserialization: Part-1[^]
XML Serialization and Deserialization: Part-2[^]
A Complete Sample of Custom Class Collection Serialization and Deserialization[^]

Try!