使用XElement附加XML

时间:2013-07-28 18:01:10

标签: c# xml linq wcf

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文件,但输出不是我预期的,它甚至会删除标记并附加在错误的位置。

1 个答案:

答案 0 :(得分: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");