[英]Append XML with XElement
PurchaseList.xml
<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>
如您所見,我希望使用XElement附加xml文件,但是輸出不是我所期望的,它甚至刪除了標簽並在錯誤的位置附加。
替換xNewBook.Add(xPurchaseBook);
使用xNewBook.Element("books").Add(xPurchaseBook);
您正在selecting user in LINQ query
中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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.