[英]Append XML with XElement
PurchaseList.xml 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 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");
Output : 输出:
<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>
Expected output : 预期产量:
<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>
As you can see, i wish to append the xml file using XElement, but output is ain't i expected, it even delete the tag and append at the wrong position. 如您所见,我希望使用XElement附加xml文件,但是输出不是我所期望的,它甚至删除了标签并在错误的位置附加。
Replace xNewBook.Add(xPurchaseBook);
替换
xNewBook.Add(xPurchaseBook);
with xNewBook.Element("books").Add(xPurchaseBook);
使用
xNewBook.Element("books").Add(xPurchaseBook);
You are selecting user in LINQ query
and adding a new item in that. 您正在
selecting user in LINQ query
中selecting user in LINQ query
并在其中添加新项。 You need to get books
element from the user and should add in that. 您需要从用户那里获取
books
元素,并应该在其中添加。
OR 要么
You should get the books
element and save the entire xDoc
instead of xNewBook
. 您应该获取
books
元素并保存整个xDoc
而不是xNewBook
。
XElement xNewBook = (from user in xDoc.Descendants("user")
where (String)user.Attribute("id") == "13004"
select user.Element("books")).Single();
and save xDoc
- 并保存
xDoc
xDoc.Save(localPath + "PurchaseList.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.