使用Linq to XML将XElement添加到XML文件中

3

使用 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>

这还是不正确的,有任何想法吗?
1个回答

1

初始的 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<Kids>
  <Child>
    <Name>Kid1</Name>
    <FirstName>hisname</FirstName>
  </Child>
</Kids>

以下代码将在现有的 XML 中添加一个新的子元素

    [Test]
    public void Test()
    {
        string filPath = @"YourKids.xml";
        var root = XElement.Load(filPath);
         var newChild =  new XElement("Child",
                                   new XElement("Name", "NewName"),
                                   new XElement("FirstName", "NewFirstName"));
         root.Add(newChild);
        root.Save(filPath);
    }

结果 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<Kids>
  <Child>
    <Name>Kid1</Name>
    <FirstName>hisname</FirstName>
  </Child>
  <Child>
    <Name>NewName</Name>
    <FirstName>NewFirstName</FirstName>
  </Child>
</Kids>

更新

保存时出现错误,应将流长度设置为0

说明

在读取现有文件后,不会删除任何数据

using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml",FileMode.Open, store))
                    {
                        var x = XElement.Load(stream);

所以当您打电话时,数据已被附加。

   x.Save(stream);
   stream.Close();

x.Save(stream);之前添加stream.SetLength(0);,这样所有数据都将被覆盖。
以下是完整版本。
            if (store.FileExists("YourKids.xml"))
            {
                using (var 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);
                    stream.SetLength(0);
                    x.Save(stream);
                    stream.Close();
                }
            }
            else
            {
                using (var 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语句。
附言:看一下resharper,它可以改善代码。

哇,谢谢你的快速回复。虽然它将新的子元素添加到我的XML文件中,但奇怪的是它保留了我的初始XML文件,并在我的初始文件下添加了结果XML文件,使XML文件看起来像:<?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>Kid1</Name> <FirstName>hisname</FirstName> </Child> </Kids><?xml version="1.0" encoding="utf-8"?> <Kids> <Child> <Name>Kid1</Name> <FirstName>hisname</FirstName> </Child> <Child> <Name>NewName</Name> <FirstName>NewFirstName</FirstName> </Child> </Kids> - user717316
看起来你保存结果不正确,root.Save(filPath)-替换现有文件。你能展示一下你的最后一段代码吗? - GSerjo
我已经编辑了我的第一篇帖子,并附上了完整的代码,这样你就可以看到我是如何保存我的xml文件的。 - user717316
谢谢你,GSerjo,非常感激。 - user717316

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接