簡體   English   中英

用XElement附加XML

[英]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 queryselecting 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM