在XML中添加元素和节点
本文关键字:节点 元素 添加 XML | 更新日期: 2023-09-27 18:26:18
我有一个应用程序正在接收以下XML,我必须添加一些额外的信息(新元素)。你能帮我理解怎么做吗?
<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>
但我需要加载XML,并在下面添加一个类似的部分
<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>
使用LINQ-to-XML
可以很容易地做到这一点,如下所示:-
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");