如何在C#中更新XML文件?

时间:2019-05-29 04:41:16

标签: c# xml asp.net-mvc

下面是我的XML文件

<MultiCentreDeals>
<DealItem>
<ID>24</ID>
<Days>
  <Day>
    <DayID>24-1</DayID>
    <DayTitle>Day 13</DayTitle>
    <Title>Meeting Point</Title>
    <HotelName>15</HotelName>
    <Description>Winter</Description>
  </Day>
  <Day>
    <DayID>24-2</DayID>
    <DayTitle>Day 2</DayTitle>
    <Title>Departure to Test</Title>
    <HotelName>54</HotelName>
    <Description>Two</Description>
 </Day>
 </Days>
 </DealItem>
<MultiCentreDeals>

首先,我要根据ID和DayID来获取数据,而不必更新属于该节点的数据。

1 个答案:

答案 0 :(得分:1)

尝试如下,

 XDocument doc = XDocument.Load(Server.MapPath(xmlfilepath));
            Dictionary<string, XElement> CompleteDealSet = doc.Descendants("DealItem").GroupBy(x => (string)x.Element("ID"), y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
            XElement Selected_Deal = CompleteDealSet[mc_ID];

            Dictionary<string, XElement> ItinerarySet = Selected_Deal.Descendants("Day").GroupBy(x => (string)x.Element("DayID"), y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
            XElement selected_Itinerary = ItinerarySet[dayID];
            selected_Itinerary.Element("DayTitle").SetValue(multicentreDay);
            selected_Itinerary.Element("Title").SetValue(itineraryTitle);
            selected_Itinerary.Element("HotelName").SetValue(hotelName);
            selected_Itinerary.Element("Description").SetValue(multidayItineraryDescription);

            doc.Save(Server.MapPath(xmlfilepath));