我将如何编辑此XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<employees>
<employee id="657434365436543" name="Joe Bloggs" group="Manager" subgroup="Deputy">
<contactDetails>
<homePhone>6535436543</homePhone>
<mobilePhone>654365436543</mobilePhone>
</contactDetails>
<personelFile>
<rightToWork>
<type>Permanent</type>
<expires>Never</expires>
</rightToWork>
<nationalInsurance>6543655543</nationalInsurance>
<startDate>01/09/2009</startDate>
</personelFile>
<holidays>
<entitlements>
<holidays>22</holidays>
<bankHolidays>8</bankHolidays>
<personalDays>1</personalDays>
</entitlements>
<taken>
<holidays>1</holidays>
<bankHolidays>0</bankHolidays>
<personalDays>0</personalDays>
</taken>
<remaining>
<holidays>21</holidays>
<bankHolidays>8</bankHolidays>
<personalDays>1</personalDays>
</remaining>
<booked>
<holidays>22</holidays>
<bankHolidays>8</bankHolidays>
<personalDays>1</personalDays>
</booked>
<remainingtobook>
<holidays>0</holidays>
<bankHolidays>0</bankHolidays>
<personalDays>0</personalDays>
</remainingtobook>
</holidays>
<shifts>
<monday>
<start>0800</start>
<end>1300</end>
</monday>
<tuesday>
<start>0800</start>
<end>1300</end>
</tuesday>
<wednesday>
<start>0800</start>
<end>1300</end>
</wednesday>
<thursday>
<start></start>
<end></end>
</thursday>
<friday>
<start>0800</start>
<end>1300</end>
</friday>
<saturday>
<start>0800</start>
<end>1200</end>
</saturday>
<sunday>
<start></start>
<end></end>
</sunday>
</shifts>
</employee>
</employees>
到目前为止,我有以下内容从XML中选择正确的员工:
XmlTextReader employeesReader = new XmlTextReader("Employees.xml");
var employeesXdoc = XDocument.Load(employeesReader);
var employees = from employee in employeesXdoc.Descendants("employee")
where employee.Attribute("id").Value.ToString() == employeeSelect.Value.ToString()
select new
{
nodes = employee.Nodes()
};
foreach (var employee in employees)
{
// WHAT TO PUT HERE?
}
我猜我找到了正确的位置来插入文件的编辑但是我需要知道如何正确编辑它然后将其保存到文件中而不会丢失其中包含的所有内容(否则我会只是覆盖整个文件。
感谢您的帮助。
答案 0 :(得分:2)
一个好主意也是使用xml-serializer-class。
您可以使用常用对象并稍后将其保存到xml中:)
答案 1 :(得分:1)
这是一个有用的链接,用于更新XML文件,而无需在每次保存时完整地重写它: http://support.microsoft.com/kb/301233
一般的想法是使用XMLDocument而不是XMLTextReader并将.xml文件加载到XMLDocument对象中。然后抓住根节点并开始导航/查询。找到要编辑的节点后,进行更改。然后在完成后,使用XMLDocument.Save(path)来保存您的chagnes。
IO流是单向Phenoma,因此您可以使用读取器/写入器,除非您想覆盖现有文件。