2013-07-28 3 views
2

PurchaseList.xmlAppend XML с XElement

<purchaseList> 
    <user id="13004"> 
     <books> 
     <book isbn="1111707154" title="Music Potter 2" author="customer" price="10" currency="RM" /> 
     </books> 
    </user> 
</purchaseList> 

WebService.cs

xDoc = XDocument.Load(serverPath + "PurchaseList.xml"); 
XElement xNewBook = (XElement)(from user in xDoc.Descendants("user") 
           where (String)user.Attribute("id") == userID 
           from books in user.Elements("books") 
           select user).Single(); 

XElement xPurchaseBook = new XElement("book", 
    new XAttribute("isbn", xISBN), 
    new XAttribute("title", xTitle), 
    new XAttribute("author", "customer"), 
    new XAttribute("price", xPrice), 
    new XAttribute("currency", xCurrency)); 
xNewBook.Add(xPurchaseBook); 
xNewBook.Save(localPath + "PurchaseList.xml"); 

Выход:

<user id="13004"> 
    <books> 
     <book isbn="1111707154" title="Music Potter 2" author="customer" price="10" currency="RM" /> 
    </books> 
    <book isbn="1439056501" title="Harry Potter" author="customer" price="10" currency="RM" /> 
</user> 

Ожидаемый результат:

<purchaseList> 
    <user id="13004"> 
     <books> 
     <!-- Should append inside here --> 
     <book isbn="1111707154" title="Music Potter 2" author="customer" price="10" currency="RM" /> 
     <book isbn="1439056501" title="Harry Potter" author="customer" price="10" currency="RM" /> 
     </books> 
    </user> 
</purchaseList> 

Как вы можете видеть, я хочу добавить xml-файл с помощью XElement, но вывод не ожидается, он даже удалит тег и добавит его в неправильное положение.

ответ

0

Заменить xNewBook.Add(xPurchaseBook);

с xNewBook.Element("books").Add(xPurchaseBook);

Вы selecting user in LINQ query и добавления нового элемента в этом. Вам нужно получить books элемент от пользователя и должен добавить к нему.

ИЛИ

Вы должны получить books элемент и сохранить весь xDoc вместо xNewBook.

XElement xNewBook = (from user in xDoc.Descendants("user") 
         where (String)user.Attribute("id") == "13004" 
         select user.Element("books")).Single(); 

и сохранить xDoc -

xDoc.Save(localPath + "PurchaseList.xml"); 
Смежные вопросы