如何在C#中读取/修改xml文件 [英] how to read/modify the xml file in C#
问题描述
感谢您阅读我的问题.
这是我的xml文件.
Thank you for reading my question.
thi is my xml file.
<rootttt>
<content>
<pre>
<aa>ma</aa>
<bb>mb</bb>
<cc>mc</cc>
<aa>ma</aa>
<bb>mb</bb>
<cc>mc</cc>
1:对于标签a,b,c,并不总是在这里,也许会丢失.
2:对于pre标签,可能很多,但至少一个.
3:修改,是,包含,删除,更改值.
如何在C#中读取/修改此xml文件?
我尝试了一些解决方案,但是我的C#不好,我做不到.有人可以给我示例代码吗?
1: for the tag a, b, c, not always here, maybe missing.
2: for the tag pre, maybe many, but at least one.
3: modify, yes, contains, deleting, changing value.
how to read / modify this xml file in C#?
i tried somet solutions, but my C# is bad,,,i can''t do it. could someone give me a sample code? thank you very much!
推荐答案
嘿,
Hey,
refer following code
XmlDocument doc = new XmlDocument();
doc.Load("path_to_input_file");
// Make changes to the document.
XmlTextWriter xtw = new XmlTextWriter("path_to_output_file", Encoding.UTF8);
doc.WriteContentTo(xtw);
祝你好运
快乐编码:)
Best Luck
Happy Coding :)
Hi,
Here a small example that uses the XmlSerializer to write data from a class into an Xml and reads it back:
using System;
using System.Xml.Serialization;
using System.IO;
namespace XmlDataSerializer
{
// The data class containing two properties
[Serializable()]
public class Data
{
public String FirstProperty { get; set; }
public int SecondProperty { get; set; }
}
// The test program
class Program
{
static void Main(string[] args)
{
Data tx = new Data();
tx.FirstProperty = "Hello Word";
tx.SecondProperty = 4711;
// Write to XML
XmlSerializer writer = new XmlSerializer(typeof(Data));
using (FileStream file = File.OpenWrite("data.xml"))
{
writer.Serialize(file, tx);
}
// Read from XML
Data rx;
XmlSerializer reader = new XmlSerializer(typeof(Data));
using (FileStream input = File.OpenRead("data.xml"))
{
rx = reader.Deserialize(input) as Data;
}
Console.WriteLine("1st = <{0}, 2nd = <{1}>", rx.FirstProperty, rx.SecondProperty);
Console.ReadLine();
}
}
}
The XML looks like that:
<?xml version="1.0"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstProperty>Hello Word</FirstProperty>
<SecondProperty>4711</SecondProperty>
</Data>
您可以参考一下.
http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTasp /a> [ ^ ]
使用.NET读取XML文件 [
You may refer this.
http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTutMellli21.aspx[^]
Reading an XML file using .NET[^]
这篇关于如何在C#中读取/修改xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!