检查现有的XML元素内容并替换它

时间:2014-04-04 00:46:22

标签: c# xml

我有一个使用以下代码写入XML的c#app:

     //Write last compliant elements to state XML if allCompliant bool == true
        if (allCompliant == true)
        {
            if (File.Exists(MainEntry.thirdPartyStateXMLPath))
            {
                XDocument doc = XDocument.Load(MainEntry.thirdPartyStateXMLPath);

                DateTime localCurrentTime = DateTime.Now;
                DateTime utcCurrentTime = DateTime.UtcNow;

                XElement root = new XElement("Compliance_Status");

                root.Add(new XElement("Last_Known_Compliant_UTC", utcCurrentTime));
                root.Add(new XElement("Last_Known_Compliant_LocalTime", localCurrentTime.ToString()));
                doc.Element("Compliance_Items").Add(root);
                doc.Save(MainEntry.thirdPartyStateXMLPath);

            }

        }

呈现以下XML:

<?xml version="1.0" encoding="utf-8"?>
<Compliance_Items>
  <Compliance_Status>
    <Last_Known_Compliant_UTC>2014-04-03T23:22:31.507088Z</Last_Known_Compliant_UTC>
    <Last_Known_Compliant_LocalTime>4/3/2014 4:22:31 PM</Last_Known_Compliant_LocalTime>
  </Compliance_Status>
</Compliance_Items>

此代码生成* Last_Known_Compliant_UTC *和* Last_Known_Compliant_LocalTime *元素和值。在后续的代码运行中,我希望它只替换现有元素的值,但是现在写入时,每次都会重新创建以下内容并在XML中保持堆叠:

<Compliance_Status>
     <Last_Known_Compliant_UTC>2014-04-03T23:22:31.507088Z</Last_Known_Compliant_UTC>
     <Last_Known_Compliant_LocalTime>4/3/2014 4:22:31 PM</Last_Known_Compliant_LocalTime>
</Compliance_Status>

如何达到预期效果?

1 个答案:

答案 0 :(得分:0)

如果您想获得特定项目并进行修改,您可以执行以下操作:

var xmlDocument = XDocument.Load("path");

var element = xmlDocument
.Descendants("Compliance_Status")
.FirstOrDefault(x => (DateTime)x.Element("Last_Known_Compliant_UTC") == someValue)

if(element != null) 
  /* update the value simply using element.Value = something 
     and save the xml file  xmlDocument.Save("path") */

如果您想用另一个元素替换元素,可以使用XElement.ReplaceWith方法。