在现有XML中添加新的XML元素

时间:2012-03-29 07:22:33

标签: .net xml

以下是我尝试在现有xml中附加节点的代码,

XmlDocument doc = new XmlDocument();
XmlNode root = doc.DocumentElement;
XmlElement elem = doc.CreateElement("price");
doc.LoadXml("<Hotel><OptionNo>1</OptionNo><StayDateRange Start=\"15/04/2012\" End=\"17/04/2012\"/><Property Id=\"31461\" CityCode=\"666\" CityName=\"MUMBAI\" CountryCode=\"246\" CountryName=\"INDIA\" StateCode=\"7332\" StateName=\"Maharashtra\" StarRating=\"1\" Chain=\"\" Status=\"Available\" HotelName=\"Airlines International Hotel\" Preferred=\"Yes\" BuiltYear=\"\" RenovationYear=\"\" NoOfFloors=\"\" Location=\"YOGA INSTITUTE RD,PRABHAT COLONY,SANTACRUZ(E),MUMB  Mumbai\" MinimumRate=\"4733.43\" Currency=\"INR\"><Address><Address1>YOGA INSTITUTE RD,PRABHAT COLONY,SANTACRUZ(E),MUMB  Mumbai</Address1><Address2/><CityCode>666</CityCode><CountryCode>246</CountryCode><PostalCode>400055</PostalCode><CityName>MUMBAI</CityName></Address><Description Name=\"Comprising of 27 rooms in total, this small budget hotel is clean and comfortable, making it the ideal choice for both business and leisure travellers. Fully air-conditioned, it features a 24-hour reception, currency exchange facilities, lift access and an on-site restaurant. Room and laundry services are also available.\" Url=\"\"/><GeoCode Code=\"\" longitude=\"\" latitude=\"\"/><Images><HotelFrontImage Url=\"\"/><Room Url=\"\"/></Images><OtherHotelImages/><Features/><Transportation/><Attractions/></Property><Rooms><Room NumberOfRooms=\"1\" RoomId=\"4511\" Description=\"Double Room\" Twin=\"No\" SupplierCode=\"HP\" SupplierId=\"4\" PropertyId=\"31461\" ExtraBed=\"0\" RateBasis=\"0\" Type=\"Double\"><Rate Id=\"4511\" Currency=\"INR\" Gross=\"9466.86\" Net=\"9466.86\" Tax=\"0\" ExtraGuestCharge=\"0.00\" AdultCount=\"2\" AdultRate=\"\" ChildCount=\"0\" ChildRate=\"\" Description=\"Bed and Breakfast\" Status=\"Available\" AllocationDetails=\"OC-84296147\"><Nights><Night Date=\"1\" Gross=\"4733.43\" Net=\"4733.43\" Tax=\"0.00\" AdultCount=\"2\" AdultRate=\"0\" ChildCount=\"0\" ChildRate=\"0\" ExtraGuestCharge=\"0\" BookedDate=\"15/04/2012\" FreeStay=\"\" RateSupplierId=\"1\" Status=\"Available\"/><Night Date=\"2\" Gross=\"4733.43\" Net=\"4733.43\" Tax=\"0.00\" AdultCount=\"2\" AdultRate=\"0\" ChildCount=\"0\" ChildRate=\"0\" ExtraGuestCharge=\"0\" BookedDate=\"16/04/2012\" FreeStay=\"\" RateSupplierId=\"1\" Status=\"Available\"/></Nights><MinStay/><DateApplyMinStay/><CancellationRules>Please see the cancellation rules</CancellationRules></Rate><Ages/><Amenities/></Room></Rooms></Hotel>");
root = doc.DocumentElement;
elem = doc.CreateElement("OtherHotelImage");
elem.InnerText = "URL";
root.AppendChild(elem);
doc.Save(Console.Out);

我尝试在指定的xml中添加新节点,该节点位于<OtherHotelImages>元素内。但它是在根元素内创建的<Hotel>

1 个答案:

答案 0 :(得分:0)

你正在调用root.AppendChild()...所以是的,它在根目录下进行。您需要遍历XML树,直到找到正确的元素 - 然后然后将新元素添加到