如何使用C#中的XDocument编辑具有相同名称的XML节点

时间:2015-12-07 06:22:29

标签: c# xml

这是我的 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>

这是我目前的代码。我需要编辑第1,第2或第3里程碑。我不知道具体的语法。我如何编辑像这样的元素里程碑[0]。

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

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

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

答案 1 :(得分:1)

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,第2或第3里程碑

从1循环到3?