简体   繁体   中英

How to Edit XML node with same name using XDocument in C#

This is my 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>

This is my current code. I need to Edit the 1st, 2nd, or 3rd Milestone. I don't know how exactly the syntax for that. How do i edit element Milestone[0] something like this.

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

You can do something like this

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

To update Nth element

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

Update This will update the second Milestone

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);
}

I need to Edit the 1st, 2nd, or 3rd Milestone

loop from 1 to 3?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM