如何使用C#将xml节点集添加到现有文件

时间:2019-06-05 07:37:28

标签: c# xml asp.net-mvc

下面是我的XML

<MultiCentreDeals>
    <DealItem>
      <ID>24</ID>
      <Days>
         <Day>
          <DayID>24-1</DayID>
          <DayTitle>Day 13</DayTitle>
      </Day>
      <Day>
          <DayID>24-2</DayID>
          <DayTitle>Day 2</DayTitle>
      </Day>
     </Days>
   </DealItem>
   <DealItem>
      <ID>25</ID>
      <Days>
         <Day>
          <DayID>25-1</DayID>
          <DayTitle>Day 3</DayTitle>
      </Day>
      <Day>
          <DayID>25-2</DayID>
          <DayTitle>Day 4</DayTitle>
      </Day>
     </Days>
   </DealItem>
</MultiCentreDeals>

首先,我想根据ID(25)选择数据并为其添加一个集合。我尝试了很多方法,却没有任何效果,有人可以告诉我该怎么做吗?我尝试通过以下方式选择属于ID(25)的特定数据,但不确定它是否正确。

  XDocument doc = XDocument.Load(Server.MapPath("/Xml/MultiCentreDealDetails.xml"));
  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());

1 个答案:

答案 0 :(得分:1)

这对我有用,

   XElement saveData = Selected_Deal.Element("Days");
   saveData.Add(new XElement("Day",
   new XElement("DayID", newDayID),
   new XElement("DayTitle", multicentreDay)));
   doc.Save(Server.MapPath("/Xml/MultiCentreDealDetails.xml"));