使用 Linq to XML,我正在尝试将 XElement 添加到现有的 XML 文件中。它必须在 Windows Phone .NET 框架中完成。目前我的 XML 文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Kids>
<Child>
<Name>Kid1</Name>
<FirstName>hisname</FirstName>
</Child>
</Kids>
and my code looks like this:
using (IsolatedStorageFileStream stream =
new IsolatedStorageFileStream("YourKids.xml", fileMode, store))
{
XDocument x = XDocument.Load(stream);
XElement t = new XElement("Child",
new XElement("Name", pName),
new XElement("FirstName", pFirstname));
t.Add(from el in x.Elements()
where el == el.Descendants("Child").Last()
select el);
x.Save(stream);
}
this doesn't do what I want to achieve. I want to add a new "Child" element to the the exisiting XML file like this :
<?xml version="1.0" encoding="utf-8"?>
<Kids>
<Child>
<Name>Kid1</Name>
<FirstName>hisname</FirstName>
</Child>
<Child>
<Name>kid2</Name>
<FirstName>SomeName</FirstName>
</Child>
</Kids>
Could use some help because I am stuck ;-)
After the tips from GSerjo, my code looks like this now:
try
{
if (store.FileExists("YourKids.xml"))
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml",FileMode.Open, store))
{
var x = XElement.Load(stream);
var t = new XElement("Child",
new XElement("Name", pName),
new XElement("FirstName", pFirstname)
);
x.Add(t);
x.Save(stream);
stream.Close();
return;
}
}
else
{
using (IsolatedStorageFileStream CreateIsf = new IsolatedStorageFileStream("YourKids.xml",FileMode.Create,store))
{
var xDoc = new XElement("Kids",
new XElement("Child",
new XElement("Name", pName),
new XElement("FirstName", pFirstname)
)
);
xDoc.Save(CreateIsf);
CreateIsf.Close();
return;
}
}
}
catch (Exception ex)
{
message = ex.Message;
}
这给了我一个这样的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<Kids>
<Child>
<Name>test</Name>
<FirstName>test</FirstName>
</Child>
</Kids><?xml version="1.0" encoding="utf-8"?>
<Kids>
<Child>
<Name>test</Name>
<FirstName>test</FirstName>
</Child>
<Child>
<Name>testing</Name>
<FirstName>testing</FirstName>
</Child>
</Kids>
哪个仍然不正确,有人有什么想法吗?