C# 用XElement追加XML
PurchaseList.xmlC# 用XElement追加XML,c#,xml,linq,wcf,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&
<purchaseList>
<user id="13004">
<books>
<book isbn="1111707154" title="Music Potter 2" author="customer" price="10" currency="RM" />
</books>
</user>
</purchaseList>
输出:
<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文件,但输出不是我所期望的,它甚至删除了标记并附加到错误的位置。ReplacexNewBook.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");
xDoc.Save(localPath + "PurchaseList.xml");