如何在C#中使用XDocument编辑同名的XML节点

本文关键字:编辑 节点 XML XDocument | 更新日期: 2023-09-27 18:25:59

这是我的XML

<MilestoneCollection>
    <Milestone>
        <Description>Departure from Origin</Description>
        <EventCode>DEP</EventCode>
        <Sequence>1</Sequence>
        <ActualDate></ActualDate>
        <ConditionReference>LOC=&lt;FirstLeg.Origin&gt;</ConditionReference>
        <ConditionType>RFP</ConditionType>
        <EstimatedDate>2015-05-10T18:07:00</EstimatedDate>
    </Milestone>
    <Milestone>
        <Description>Departure from Origin</Description>
        <EventCode>DEP</EventCode>
        <Sequence>1</Sequence>
        <ActualDate></ActualDate>
        <ConditionReference>LOC=&lt;FirstLeg.Origin&gt;</ConditionReference>
        <ConditionType>RFP</ConditionType>
        <EstimatedDate>2015-05-10T18:07:00</EstimatedDate>
    </Milestone>
    <Milestone>
        <Description>Arrival at Destination</Description>
        <EventCode>ARV</EventCode>
        <Sequence>2</Sequence>
        <ActualDate></ActualDate>
        <ConditionReference>LOC=&lt;LastLeg.Destination&gt;</ConditionReference>
        <ConditionType>RFP</ConditionType>
        <EstimatedDate>2015-05-11T14:02:00</EstimatedDate>
    </Milestone>
    <Milestone>
        <Description>Arrival at Destination</Description>
        <EventCode>ARV</EventCode>
        <Sequence>2</Sequence>
        <ActualDate></ActualDate>
        <ConditionReference>LOC=&lt;LastLeg.Destination&gt;</ConditionReference>
        <ConditionType>RFP</ConditionType>
        <EstimatedDate></EstimatedDate>
    </Milestone>
</MilestoneCollection>

这是我当前的代码。我需要编辑第一个、第二个或第三个里程碑。我不知道它的确切语法是什么。我该如何编辑元素Milestone[0]之类的内容。

XDocument doc = XDocument.Load(sample.xml);
var xmldocu = doc.Descendants("MilestoneCollection");

如何在C#中使用XDocument编辑同名的XML节点

您可以执行类似的操作

XDocument doc = XDocument.Load(sample.xml);
doc.Descendants("Milestone").First()
   .Descendants("EstimatedDate").First().Value = DateTime.Now.ToString();

更新第N个元素

doc.Descendants("Milestone")
   .ElementAt(2).Descendants("EstimatedDate").First().Value = DateTime.Now.ToString();

更新这将更新第二个里程碑

doc.Elements("MilestoneCollection")
                .Elements("Milestone")
                .ElementAt(1)
                .Descendants("EstimatedDate")
                .First()
                .Value=DateTime.Now.ToString();
var xmldocu = xml.Descendants("Milestone").ToArray();
for (var i = 0; i < 3 && i < xmldocu.Length; i++)
{
    var ele = xmldocu[i];
    ele.Element("EstimatedDate").SetValue(DateTime.Now);
}

我需要编辑第一、第二或第三个里程碑

从1循环到3?