c# - 使用 XElement 追加 XML

标签 c# xml linq wcf

采购 list .xml

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

网络服务.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);

您正在在 LINQ 查询中选择用户 并在其中添加一个新项目。您需要从用户那里获取 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");

关于c# - 使用 XElement 追加 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911144/

相关文章:

c# - 如何在将记录插入数据库后立即在组合框中显示主键 C#?

c# - Entity Framework DbGeography 没有正确计算面积?

javascript - 如何判断我的 XML 是否已正确解析为 JSON?

c# - 如何按 2 个值平整 IEnumerable?

c# - 如何确定一个 JSON 对象是否只包含一个特定的键?

c# - 如何以编程方式在 Windows 操作系统中打开 "Network Discovery"?

c# - EnvDTE 从 CodeElement 中检索数据类型

java - 如何在 Xpath 中获取节点值 - Java

xml - JSPX namespace 对 EL 函数不可见?

c# - 在System.Linq.Dynamic.Select()中,如何简单的处理空对象引用?