Skip to main content
 首页 » 编程设计

c#之从 xml 加载信息,使用 c# 保存相关(更改)信息

2024年02月23日16JustinYoung

friend 们, 我的学校项目有一个 xml 数据文件:

<patients> 
<patient> 
<regNo>2012/Mar/003</regNo> 
<name>Jhon</name> 
<add>Somewhere</add> 
<mobile>0000</mobile> 
. 
. 
. 
<stay>2</stay> 
<costofroom>100</costofroom> 
<total>200</total> 
</patient> 
</patients> 

我的 Windowsform“EditPatients_Load”能够获取患者 Jhon 的所有信息,现在假设管理员需要更改表单中的一些信息并重新提交。

Then how to write back all values to Jhon's account in the same xml file????

我无法组成逻辑代码,即使我检查节点 if (patients.paptient.name = "nameComboBox.text").... 如何确保我正在写其他值合适的地方?

Rgrdz,

请您参考如下方法:

试试这个:

//string xml =  
            //@"<patients><patient><regNo>2012/Mar/003</regNo><name>Jhon</name><add>Somewhere 
            //</add><mobile>0000</mobile><stay>2</stay><costofroom>100</costofroom><total>200</total> 
            //</patient></patients>"; 
            XDocument xmlDoc = XDocument.Load(@"c:\abc.xml"); 
            var items = (from item in xmlDoc.Descendants("patient") 
                         where item.Element("name").Value == "Jhon" 
                         select item); 
            if (items.Count() > 0) 
            { 
                var item = items.First(); 
                item.SetElementValue("add", "New New Address"); 
                xmlDoc.Save(@"c:\abc.xml", SaveOptions.None); 
            } 

您可以使用

获取单个元素
var item = (from item in xmlDoc.Descendants("patient") 
                             where item.Element("name").Value == "Jhon" 
                             select item).FirstOrDefault(); 

然后使用 SetElementValue() 方法更新它。

//更新的Xml

<?xml version="1.0" encoding="utf-8"?> 
<patients> 
  <patient> 
    <regNo>2012/Mar/003</regNo> 
    <name>Jhon</name> 
    <add>New Address</add> 
    <mobile>0000</mobile> 
    <stay>2</stay> 
    <costofroom>100</costofroom> 
    <total>200</total> 
  </patient> 
</patients> 

引用:
Update XML with C# using Linq