user5625080
user5625080

Reputation:

Add Elements And Node in XML

I have an application that is receiving the following XML, and I have to add some extra information (new elements). Could you please help me understand how to do it?

<Feed>
  <Claims>
    <Claim>
      <ClaimID>123</ClaimID>
      <Reference>245</Reference>
      <AccidentDetails>
        <IncidentDate>2015-08-05</IncidentDate>
      </AccidentDetails>
      <DriverDetails>
        <DriverFirstName>Text</DriverFirstName>
        <DriverLastName>Text</DriverLastName>
      </DriverDetails>
      <ClientVehicleDetails>
        <VehicleLegallyDriveable>Yes</VehicleLegallyDriveable>
        <VehicleLocation>In Use</VehicleLocation>
      </ClientVehicleDetails>
    </Claim>
  </Claims>
</Feed>

But I need to load the XML and add a section like below

<Feed>
  //This is the section I need to add to my XML
  <Control>
    <Username>Test</Username>
    <Password>TestPass</Password>
  </Control>
  //The following XML will remain the same
  <Claims>
    <Claim>
      <ClaimID>123</ClaimID>
      <Reference>245</Reference>
      <AccidentDetails>
        <IncidentDate>2015-08-05</IncidentDate>
      </AccidentDetails>
      <DriverDetails>
        <DriverFirstName>Text</DriverFirstName>
        <DriverLastName>Text</DriverLastName>
      </DriverDetails>
      <ClientVehicleDetails>
        <VehicleLegallyDriveable>Yes</VehicleLegallyDriveable>
        <VehicleLocation>In Use</VehicleLocation>
      </ClientVehicleDetails>
    </Claim>
  </Claims>
</Feed>

Upvotes: 1

Views: 45

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

You can easily do it with LINQ-to-XML like this:-

XDocument xdoc = XDocument.Load("ClaimXMLFile");
XDocument xdoc2 = new XDocument(new XElement("Feed",
                                  new XElement("Control",
                                      new XElement("Username", "TestPass"),
                                      new XElement("Password", "Test")),
                                            xdoc.Root));
xdoc2.Save(@"NewXMLFileName");

Upvotes: 1

Related Questions